Debian Codegraph @

test/logger.go

raw
1 package test
2
3 import (
4 "context"
5 "io"
6 "log/slog"
7 "os"
8 "time"
9
10 "github.com/slackhq/nebula/logging"
11 )
12
13 // NewLogger returns a *slog.Logger suitable for use in tests. Output goes to
14 // io.Discard by default; set TEST_LOGS=1 (info), 2 (debug), or 3 (trace) to
15 // stream output to stderr for local debugging.
16 func NewLogger() *slog.Logger {
17 v := os.Getenv("TEST_LOGS")
18 if v == "" {
19 return slog.New(slog.DiscardHandler)
20 }
21
22 level := slog.LevelInfo
23 switch v {
24 case "2":
25 level = slog.LevelDebug
26 case "3":
27 level = logging.LevelTrace
28 }
29 return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level}))
30 }
31
32 // NewLoggerWithOutput returns a *slog.Logger whose text output is captured by
33 // w. Timestamps are suppressed so tests can assert on exact output without
34 // baking the current time into expected strings.
35 func NewLoggerWithOutput(w io.Writer) *slog.Logger {
36 return slog.New(&stripTimeHandler{inner: slog.NewTextHandler(w, nil)})
37 }
38
39 // NewLoggerWithOutputAndLevel is NewLoggerWithOutput with an explicit level
40 // so tests can exercise Enabled-gated paths.
41 func NewLoggerWithOutputAndLevel(w io.Writer, level slog.Level) *slog.Logger {
42 return slog.New(&stripTimeHandler{inner: slog.NewTextHandler(w, &slog.HandlerOptions{Level: level})})
43 }
44
45 // NewJSONLoggerWithOutput returns a *slog.Logger emitting JSON to w with
46 // timestamps suppressed, for tests that pin the JSON shape.
47 func NewJSONLoggerWithOutput(w io.Writer, level slog.Level) *slog.Logger {
48 return slog.New(&stripTimeHandler{inner: slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level})})
49 }
50
51 // stripTimeHandler zeros each record's time before delegating so slog's
52 // built-in handlers skip emitting the time attribute. Used to avoid
53 // timestamp-dependent assertions in tests without resorting to ReplaceAttr.
54 type stripTimeHandler struct {
55 inner slog.Handler
56 }
57
58 func (h *stripTimeHandler) Enabled(ctx context.Context, l slog.Level) bool {
59 return h.inner.Enabled(ctx, l)
60 }
61
62 func (h *stripTimeHandler) Handle(ctx context.Context, r slog.Record) error {
63 r.Time = time.Time{}
64 return h.inner.Handle(ctx, r)
65 }
66
67 func (h *stripTimeHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
68 return &stripTimeHandler{inner: h.inner.WithAttrs(attrs)}
69 }
70
71 func (h *stripTimeHandler) WithGroup(name string) slog.Handler {
72 return &stripTimeHandler{inner: h.inner.WithGroup(name)}
73 }