Skip to content

Commit

Permalink
log: default JSON log handler should log all verbosity levels (ethere…
Browse files Browse the repository at this point in the history
…um#29471)


Co-authored-by: lightclient <[email protected]>
  • Loading branch information
Roberto Bayardo and lightclient authored Apr 6, 2024
1 parent ccb76c0 commit 8876868
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
4 changes: 2 additions & 2 deletions internal/debug/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
7 changes: 7 additions & 0 deletions log/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
})
}

Expand Down
19 changes: 19 additions & 0 deletions log/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 8876868

Please sign in to comment.