Debian Codegraph @

slogtest/slogtest.go

raw symbols SCIP
1 // Package slogtest provides utilities for emitting test logs using clog.
2 //
3 // func TestExample(t *testing.T) {
4 // ctx := slogtest.Context(t)
5 // clog.FromContext(ctx).With("foo", "bar").Info("hello world")
6 // }
7 //
8 // This produces the following test output:
9 //
10 // === RUN TestExample
11 // slogtest.go:24: level=INFO source=/path/to/example_test.go:13 msg="hello world" foo=bar
12 //
13 // This package is intended to be used in tests only.
14 //
15 // In Go 1.24, *testing.T etc added `t.Context()` methods, which return a
16 // context.Context to be used in tests. You can use `clog.FromContext(t.Context())`
17 // to get a logger in tests instead, and configure the default logger to get the
18 // same logging behavior as `slogtest.Context(t)`.
19 package slogtest
20
21 import (
22 "context"
23 "io"
24 "log/slog"
25 "strings"
26 "testing"
27
28 "github.com/chainguard-dev/clog"
29 )
30
31 var _ io.Writer = &logAdapter{}
32
33 type logAdapter struct{ l Logger }
34
35 func (l *logAdapter) Write(b []byte) (int, error) {
36 l.l.Log(strings.TrimSuffix(string(b), "\n"))
37 return len(b), nil
38 }
39
40 var _ Logger = (*testing.T)(nil)
41 var _ Logger = (*testing.B)(nil)
42 var _ Logger = (*testing.F)(nil)
43
44 type Logger interface {
45 Log(args ...any)
46 Context() context.Context
47 }
48
49 // TestLogger gets a logger to use in unit and end to end tests.
50 // This logger is configured to log at debug level.
51 func TestLogger(t Logger) *clog.Logger {
52 return clog.New(slog.NewTextHandler(&logAdapter{l: t}, &slog.HandlerOptions{
53 Level: slog.LevelDebug,
54 AddSource: true,
55 ReplaceAttr: RemoveTime,
56 }))
57 }
58
59 // TestLoggerWithOptions gets a logger to use in unit and end to end tests.
60 func TestLoggerWithOptions(t Logger, opts *slog.HandlerOptions) *clog.Logger {
61 return clog.New(slog.NewTextHandler(&logAdapter{l: t}, opts))
62 }
63
64 // Context returns a context with a logger to be used in tests.
65 func Context(t Logger) context.Context {
66 return clog.WithLogger(t.Context(), TestLogger(t))
67 }
68
69 // TestContextWithLogger returns a context with a logger to be used in tests
70 //
71 // Deprecated: Use Context instead.
72 func TestContextWithLogger(t Logger) context.Context { return Context(t) }
73
74 // RemoveTime removes the top-level time attribute.
75 // It is intended to be used as a ReplaceAttr function,
76 // to make example output deterministic.
77 //
78 // This is taken from slog/internal/slogtest.RemoveTime.
79 func RemoveTime(groups []string, a slog.Attr) slog.Attr {
80 if a.Key == slog.TimeKey && len(groups) == 0 {
81 return slog.Attr{}
82 }
83 return a
84 }