stop default JSON log handler from suppressing records w/ more than INFO verbosity

This commit is contained in:
Roberto Bayardo 2024-04-05 11:53:25 -07:00
parent 7ee9a6e89f
commit 1c1feabb94
No known key found for this signature in database
GPG key ID: BAD75F1206851CC1
2 changed files with 26 additions and 0 deletions

View file

@ -115,8 +115,15 @@ func (l *leveler) Level() slog.Level {
// JSONHandler returns a handler which prints records in JSON format. // JSONHandler returns a handler which prints records in JSON format.
func JSONHandler(wr io.Writer) slog.Handler { func JSONHandler(wr io.Writer) slog.Handler {
return JSONHandlerWithLevel(wr, levelMaxVerbosity)
}
// JSONHandler returns a handler which prints records in JSON format that are less than or equal to
// the specified verbosity level.
func JSONHandlerWithLevel(wr io.Writer, level slog.Level) slog.Handler {
return slog.NewJSONHandler(wr, &slog.HandlerOptions{ return slog.NewJSONHandler(wr, &slog.HandlerOptions{
ReplaceAttr: builtinReplaceJSON, ReplaceAttr: builtinReplaceJSON,
Level: &leveler{level},
}) })
} }

View file

@ -50,6 +50,25 @@ func TestTerminalHandlerWithAttrs(t *testing.T) {
} }
} }
// Make sure the default json handler outputs debug log lines
func TestJSONHandler(t *testing.T) {
out := new(bytes.Buffer)
handler := JSONHandler(out)
logger := slog.New(handler)
logger.Debug("hi there")
if len(out.String()) == 0 {
t.Error("expected non-empty debug log output from default JSON Handler")
}
out.Reset()
handler = JSONHandlerWithLevel(out, slog.LevelInfo)
logger = slog.New(handler)
logger.Debug("hi there")
if len(out.String()) != 0 {
t.Errorf("expected empty debug log output, but got: %v", out.String())
}
}
func BenchmarkTraceLogging(b *testing.B) { func BenchmarkTraceLogging(b *testing.B) {
SetDefault(NewLogger(NewTerminalHandler(os.Stderr, true))) SetDefault(NewLogger(NewTerminalHandler(os.Stderr, true)))
b.ResetTimer() b.ResetTimer()