-
Notifications
You must be signed in to change notification settings - Fork 487
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | ||
} |