Skip to content

Commit

Permalink
slogadapter: check for log level being enabled (#5264)
Browse files Browse the repository at this point in the history
The custom log.Logger implementation wrapping around a slog.Handler must
check to see if a level is enabled before logging log lines.
  • Loading branch information
rfratto authored Sep 21, 2023
1 parent 01498ea commit b264e6b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
3 changes: 3 additions & 0 deletions internal/slogadapter/gokit.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,8 @@ func (sa slogAdapter) Log(kvps ...interface{}) error {
})
}

if !sa.h.Enabled(context.Background(), rec.Level) {
return nil
}
return sa.h.Handle(context.Background(), rec)
}
38 changes: 38 additions & 0 deletions internal/slogadapter/gokit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package slogadapter

import (
"bytes"
"log/slog"
"testing"

"github.com/go-kit/log/level"
"github.com/stretchr/testify/require"
)

func TestFiltersLogs(t *testing.T) {
var buf bytes.Buffer
h := slog.NewTextHandler(&buf, &slog.HandlerOptions{
Level: slog.LevelWarn,

ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
// Drop timestamps for reproducible tests.
if a.Key == slog.TimeKey {
return slog.Attr{}
}

return a
},
})

l := GoKit(h)
level.Debug(l).Log("msg", "debug level log")
level.Info(l).Log("msg", "info level log")
level.Warn(l).Log("msg", "warn level log")
level.Error(l).Log("msg", "error level log")

expect := `level=WARN msg="warn level log"
level=ERROR msg="error level log"
`

require.Equal(t, expect, buf.String())
}

0 comments on commit b264e6b

Please sign in to comment.