Skip to content

Commit

Permalink
Pull request 110: imp-osutil-slogutil
Browse files Browse the repository at this point in the history
Squashed commit of the following:

commit c4b2739
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Thu Jun 20 22:03:42 2024 +0300

    all: imp osutil, slogutil
  • Loading branch information
ainar-g committed Jun 21, 2024
1 parent 4074c93 commit aa1be2f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
19 changes: 19 additions & 0 deletions logutil/slogutil/slogutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"log/slog"
"os"
"runtime/debug"
"strings"
)

// Additional key constants.
Expand Down Expand Up @@ -131,6 +132,24 @@ func PrintStack(ctx context.Context, l *slog.Logger, lvl slog.Level) {
}
}

// PrintLines splits s and logs the lines to l using the given level, including
// empty lines.
func PrintLines(ctx context.Context, l *slog.Logger, lvl slog.Level, msg, s string) {
lines := strings.Split(s, "\n")
for i, line := range lines {
l.Log(ctx, lvl, msg, "line_num", i+1, "line", line)
}
}

// PrintByteLines splits b and logs the lines to l using the given level,
// including empty lines.
func PrintByteLines(ctx context.Context, l *slog.Logger, lvl slog.Level, msg string, b []byte) {
lines := bytes.Split(b, []byte{'\n'})
for i, line := range lines {
l.Log(ctx, lvl, msg, "line_num", i+1, "line", line)
}
}

// bufferedTextHandler is a combination of one bytes buffer and a text handler
// that writes to it.
type bufferedTextHandler struct {
Expand Down
18 changes: 18 additions & 0 deletions logutil/slogutil/slogutil_example_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package slogutil_test

import (
"context"
"log/slog"

"github.com/AdguardTeam/golibs/logutil/slogutil"
)

Expand Down Expand Up @@ -54,3 +57,18 @@ func ExampleNew_text() {
// level=INFO msg="group test info" test_group.time="too late"
// level=DEBUG msg="group test debug" test_group.time="too late"
}

func ExamplePrintLines() {
text := `A Very Long Text
This is a very long text with many lines.`
l := slogutil.New(nil)

ctx := context.Background()
slogutil.PrintLines(ctx, l, slog.LevelInfo, "my text", text)

// Output:
// INFO my text line_num=1 line="A Very Long Text"
// INFO my text line_num=2 line=""
// INFO my text line_num=3 line="This is a very long text with many lines."
}
5 changes: 3 additions & 2 deletions osutil/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ type ExitCode = int

// Exit status constants.
const (
ExitCodeSuccess ExitCode = 0
ExitCodeFailure ExitCode = 1
ExitCodeSuccess ExitCode = 0
ExitCodeFailure ExitCode = 1
ExitCodeArgumentError ExitCode = 2
)

0 comments on commit aa1be2f

Please sign in to comment.