Skip to content

Commit

Permalink
slogutil: replace level name
Browse files Browse the repository at this point in the history
  • Loading branch information
Mizzick committed Sep 27, 2024
1 parent 1aa7a3a commit e9b9a24
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
34 changes: 30 additions & 4 deletions logutil/slogutil/slogutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,7 @@ func New(c *Config) (l *slog.Logger) {
return newDefault(output, lvl, c.AddTimestamp)
}

var replaceAttr func(groups []string, a slog.Attr) (res slog.Attr)
if !c.AddTimestamp {
replaceAttr = RemoveTime
}
replaceAttr := replaceAttributes(!c.AddTimestamp)

var h slog.Handler
switch format {
Expand Down Expand Up @@ -103,6 +100,35 @@ func newDefault(output io.Writer, lvl slog.Level, addTimestamp bool) (l *slog.Lo
return slog.New(h)
}

// replaceAttributes is a function that returns
// [slog.HandlerOptions.ReplaceAttr] for provided parameters.
func replaceAttributes(removeTime bool) func(groups []string, a slog.Attr) (res slog.Attr) {
if !removeTime {
return ReplaceLevel
}

return func(groups []string, a slog.Attr) (res slog.Attr) {
return ReplaceLevel(groups, RemoveTime(groups, a))
}
}

// ReplaceLevel is a function for [slog.HandlerOptions.ReplaceAttr] that adds
// [LevelTrace] custom name for level attribute.
func ReplaceLevel(groups []string, a slog.Attr) (res slog.Attr) {
if len(groups) > 0 {
return a
}

if a.Key == slog.LevelKey {
lvl := a.Value.Any().(slog.Level)
if lvl == LevelTrace {
a.Value = slog.StringValue("TRACE")
}
}

return a
}

// RemoveTime is a function for [slog.HandlerOptions.ReplaceAttr] that removes
// the "time" attribute.
func RemoveTime(groups []string, a slog.Attr) (res slog.Attr) {
Expand Down
9 changes: 5 additions & 4 deletions logutil/slogutil/slogutil_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,16 @@ This is a very long text with many lines.`

func ExampleNew_trace() {
l := slogutil.New(&slogutil.Config{
Level: slogutil.LevelTrace,
Format: slogutil.FormatText,
Level: slogutil.LevelTrace,
})

l.Log(context.Background(), slogutil.LevelTrace, "test trace")
l.Info("test info")
l.Debug("test debug")

// Output:
// DEBUG-4 test trace
// INFO test info
// DEBUG test debug
// level=TRACE msg="test trace"
// level=INFO msg="test info"
// level=DEBUG msg="test debug"
}

0 comments on commit e9b9a24

Please sign in to comment.