From b264e6bb968cb8a614245348d23099711a868393 Mon Sep 17 00:00:00 2001 From: Robert Fratto Date: Thu, 21 Sep 2023 10:17:53 -0400 Subject: [PATCH] slogadapter: check for log level being enabled (#5264) The custom log.Logger implementation wrapping around a slog.Handler must check to see if a level is enabled before logging log lines. --- internal/slogadapter/gokit.go | 3 +++ internal/slogadapter/gokit_test.go | 38 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 internal/slogadapter/gokit_test.go diff --git a/internal/slogadapter/gokit.go b/internal/slogadapter/gokit.go index 72e3dfee4597..598e8a28b7df 100644 --- a/internal/slogadapter/gokit.go +++ b/internal/slogadapter/gokit.go @@ -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) } diff --git a/internal/slogadapter/gokit_test.go b/internal/slogadapter/gokit_test.go new file mode 100644 index 000000000000..05fe9694f089 --- /dev/null +++ b/internal/slogadapter/gokit_test.go @@ -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()) +}