log: default JSON log handler should log all verbosity levels (#29471)

Co-authored-by: lightclient <lightclient@protonmail.com>
pull/29474/head
Roberto Bayardo 6 months ago committed by GitHub
parent ccb76c01d7
commit 8876868bb8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 4
      internal/debug/flags.go
  2. 7
      log/handler.go
  3. 19
      log/logger_test.go

@ -231,9 +231,9 @@ func Setup(ctx *cli.Context) error {
case ctx.Bool(logjsonFlag.Name):
// Retain backwards compatibility with `--log.json` flag if `--log.format` not set
defer log.Warn("The flag '--log.json' is deprecated, please use '--log.format=json' instead")
handler = log.JSONHandler(output)
handler = log.JSONHandlerWithLevel(output, log.LevelInfo)
case logFmtFlag == "json":
handler = log.JSONHandler(output)
handler = log.JSONHandlerWithLevel(output, log.LevelInfo)
case logFmtFlag == "logfmt":
handler = log.LogfmtHandler(output)
case logFmtFlag == "", logFmtFlag == "terminal":

@ -115,8 +115,15 @@ func (l *leveler) Level() slog.Level {
// JSONHandler returns a handler which prints records in JSON format.
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{
ReplaceAttr: builtinReplaceJSON,
Level: &leveler{level},
})
}

@ -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) {
SetDefault(NewLogger(NewTerminalHandler(os.Stderr, true)))
b.ResetTimer()

Loading…
Cancel
Save