-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger_test.go
More file actions
414 lines (318 loc) · 10.3 KB
/
Copy pathlogger_test.go
File metadata and controls
414 lines (318 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package logger
import (
"bytes"
"context"
"errors"
"log/slog"
"os"
"os/exec"
"strings"
"sync"
"testing"
"time"
"github.com/fatih/color"
)
func TestMain(m *testing.M) {
color.NoColor = true // the pretty handler's output is compared as plain text
os.Exit(m.Run())
}
func jsonCtx(t *testing.T, opts ...LoggerOpt) (context.Context, *bytes.Buffer) {
t.Helper()
buf := new(bytes.Buffer)
opts = append([]LoggerOpt{WithWriter(buf), WithLevel(LevelDebug)}, opts...)
return NewLoggerContext(context.Background(), opts...), buf
}
func prettyCtx(t *testing.T, opts ...LoggerOpt) (context.Context, *bytes.Buffer) {
t.Helper()
return jsonCtx(t, append([]LoggerOpt{Local()}, opts...)...)
}
// Fatal must terminate the process: a panic would be recoverable and would
// change the exit code.
func TestFatalExitsWithCode1(t *testing.T) {
if os.Getenv("LOGGER_TEST_FATAL") == "1" {
Fatal(context.Background(), "boom")
return
}
cmd := exec.Command(os.Args[0], "-test.run=TestFatalExitsWithCode1")
cmd.Env = append(os.Environ(), "LOGGER_TEST_FATAL=1")
var exitErr *exec.ExitError
if err := cmd.Run(); !errors.As(err, &exitErr) || exitErr.ExitCode() != 1 {
t.Fatalf("want exit status 1, got %v", err)
}
}
// A message carrying a literal % must not be run through printf when no
// formatting arguments are supplied.
func TestFormattedLiteralPercent(t *testing.T) {
ctx, buf := jsonCtx(t)
// Called through a func value so that vet's printf check, which now covers
// Infof directly, does not reject the deliberately arg-less format string.
logf := Infof
logf(ctx, "disk usage 90% of quota")
if !strings.Contains(buf.String(), "disk usage 90% of quota") {
t.Fatalf("message was mangled: %s", buf.String())
}
}
func TestFormattedWithArgs(t *testing.T) {
ctx, buf := jsonCtx(t)
Errorf(ctx, "user %d not found", 42)
if !strings.Contains(buf.String(), "user 42 not found") {
t.Fatalf("message was not formatted: %s", buf.String())
}
}
// The attribute family must emit structured fields, not printf noise.
func TestAttrsReachOutput(t *testing.T) {
ctx, buf := jsonCtx(t)
Info(ctx, "user login", "user_id", 42)
out := buf.String()
if !strings.Contains(out, `"user_id":42`) || strings.Contains(out, "EXTRA") {
t.Fatalf("attrs did not reach structured output: %s", out)
}
}
func TestContextAttrsAccumulate(t *testing.T) {
for _, tc := range []struct {
name string
opts []LoggerOpt
}{
{"json", nil},
{"pretty", []LoggerOpt{Local()}},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, buf := jsonCtx(t, tc.opts...)
ctx = WithAttrs(ctx, slog.String("a", "1"), slog.String("b", "2"))
Info(ctx, "two attrs")
out := buf.String()
if !strings.Contains(out, `"a"`) || !strings.Contains(out, `"b"`) {
t.Fatalf("an earlier context attr was dropped: %s", out)
}
})
}
}
func TestPrettyGroupKeepsEarlierAttrs(t *testing.T) {
ctx, buf := prettyCtx(t)
ctx = WithAttrs(ctx, slog.String("outer", "1"))
ctx = WithGroup(ctx, "req")
ctx = WithAttrs(ctx, slog.String("id", "abc"))
Info(ctx, "grouped")
out := buf.String()
if !strings.Contains(out, `"outer"`) {
t.Fatalf("attr set before the group was dropped: %s", out)
}
if !strings.Contains(out, `"req.id"`) {
t.Fatalf("attr set inside the group was not prefixed: %s", out)
}
}
// A record's own attrs must be nested under the group the context is in.
func TestPrettyRecordAttrsTakeGroupPrefix(t *testing.T) {
ctx, buf := prettyCtx(t)
ctx = WithGroup(ctx, "req")
Info(ctx, "grouped", "id", "abc")
if out := buf.String(); !strings.Contains(out, `"req.id"`) {
t.Fatalf("record attr was not prefixed by the group: %s", out)
}
}
// The levels this package adds must be named, not printed as slog offsets such as
// ERROR+92 or INFO+2.
func TestCustomLevelNames(t *testing.T) {
levels := map[slog.Level]string{
LevelDebug: "DEBUG",
LevelInfo: "INFO",
LevelNotice: "NOTICE",
LevelWarn: "WARNING",
LevelError: "ERROR",
LevelCritical: "CRITICAL",
LevelAlert: "ALERT",
LevelEmergency: "EMERGENCY",
}
for lvl, want := range levels {
if got := LevelName(lvl); got != want {
t.Errorf("LevelName(%v) = %q, want %q", lvl, got, want)
}
if got := MapLevel(want); got != lvl {
t.Errorf("MapLevel(%q) = %v, want %v (LevelName and MapLevel must round-trip)", want, got, lvl)
}
ctx, buf := jsonCtx(t)
log(ctx, lvl, "msg")
if out := buf.String(); !strings.Contains(out, `"level":"`+want+`"`) {
t.Errorf("json handler labelled %v as %s, want %s", lvl, out, want)
}
pctx, pbuf := prettyCtx(t)
log(pctx, lvl, "msg")
if out := pbuf.String(); !strings.Contains(out, want+":") {
t.Errorf("pretty handler labelled %v as %s, want %s", lvl, out, want)
}
}
}
// The pretty timestamp used 15:05:05, which prints the second twice and never the
// minute.
func TestPrettyTimestampLayout(t *testing.T) {
buf := new(bytes.Buffer)
h := prettyHandlerOptions{SlogOpts: &slog.HandlerOptions{Level: LevelDebug}}.newPrettyHandler(buf)
at := time.Date(2026, time.August, 30, 15, 4, 5, 0, time.UTC)
if err := h.Handle(context.Background(), slog.NewRecord(at, LevelInfo, "msg", 0)); err != nil {
t.Fatal(err)
}
if out := buf.String(); !strings.Contains(out, "[15:04:05.000]") {
t.Fatalf("want [15:04:05.000] in %q", out)
}
}
// The source must name the caller of the exported function, not this package.
func TestSourceNamesTheCaller(t *testing.T) {
for _, tc := range []struct {
name string
opts []LoggerOpt
}{
{"json", nil},
{"pretty", []LoggerOpt{Local()}},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, buf := jsonCtx(t, append(tc.opts, WithSource())...)
Info(ctx, "who is the caller?")
out := buf.String()
if !strings.Contains(out, "logger_test.go") {
t.Fatalf("source does not name the caller: %s", out)
}
if strings.Contains(out, "logger.go") {
t.Fatalf("source names this package instead of the caller: %s", out)
}
})
}
}
// WithSource was accepted and then ignored by the JSON handler.
func TestWithSourceIsHonoured(t *testing.T) {
ctx, buf := jsonCtx(t, WithSource())
Info(ctx, "sourced")
if out := buf.String(); !strings.Contains(out, `"source"`) {
t.Fatalf("WithSource emitted no source field: %s", out)
}
off, offBuf := jsonCtx(t)
Info(off, "not sourced")
if out := offBuf.String(); strings.Contains(out, `"source"`) {
t.Fatalf("source was emitted without WithSource: %s", out)
}
}
func TestEnabled(t *testing.T) {
ctx, _ := jsonCtx(t, WithLevel(LevelWarn))
if Enabled(ctx, LevelInfo) {
t.Error("info must not be enabled at warn level")
}
if !Enabled(ctx, LevelError) {
t.Error("error must be enabled at warn level")
}
}
func TestBuilderDefaultsToInfo(t *testing.T) {
buf := new(bytes.Buffer)
ctx := NewLoggerContext(context.Background(), WithWriter(buf))
Debug(ctx, "dropped")
if buf.Len() != 0 {
t.Fatalf("debug must be filtered at the default level, got %s", buf.String())
}
Info(ctx, "kept")
if buf.Len() == 0 {
t.Fatal("info must pass at the default level")
}
}
// A *slog.LevelVar passed to WithLevel keeps the level adjustable after the logger
// is built.
func TestWithLevelVarIsAdjustable(t *testing.T) {
buf := new(bytes.Buffer)
lvl := new(slog.LevelVar)
lvl.Set(LevelError)
ctx := NewLoggerContext(context.Background(), WithWriter(buf), WithLevel(lvl))
Info(ctx, "dropped")
if buf.Len() != 0 {
t.Fatalf("info must be filtered at error level, got %s", buf.String())
}
lvl.Set(LevelDebug)
Info(ctx, "kept")
if buf.Len() == 0 {
t.Fatal("info must pass once the level var is lowered")
}
}
func TestWithErrorWriterRoutesByLevel(t *testing.T) {
out, errOut := new(bytes.Buffer), new(bytes.Buffer)
ctx := NewLoggerContext(context.Background(),
WithWriter(out), WithErrorWriter(errOut), WithLevel(LevelDebug))
Info(ctx, "ordinary")
Error(ctx, "broken")
if !strings.Contains(out.String(), "ordinary") || strings.Contains(out.String(), "broken") {
t.Fatalf("stdout writer got the wrong records: %s", out.String())
}
if !strings.Contains(errOut.String(), "broken") || strings.Contains(errOut.String(), "ordinary") {
t.Fatalf("error writer got the wrong records: %s", errOut.String())
}
}
// SetLevel rebuilt the global logger over os.Stdout, silently discarding whatever
// SetGlobalLogger had installed.
func TestSetLevelKeepsTheInstalledLogger(t *testing.T) {
restoreGlobal(t)
buf := new(bytes.Buffer)
lvl := new(slog.LevelVar)
lvl.Set(LevelDebug)
SetGlobalLogger(slog.New(newLoggerHandler(lvl, false, buf)))
SetLevel(LevelWarn)
Error(context.Background(), "does this reach my buffer?")
if !strings.Contains(buf.String(), "does this reach my buffer?") {
t.Fatalf("SetLevel redirected the installed logger, buffer holds %q", buf.String())
}
}
func TestSetLevelFiltersTheDefaultLogger(t *testing.T) {
restoreGlobal(t)
buf := new(bytes.Buffer)
globalLogger.Store(slog.New(newLoggerHandler(globalLevel, false, buf)))
SetLevel(LevelError)
Info(context.Background(), "dropped")
if buf.Len() != 0 {
t.Fatalf("SetLevel did not raise the level, got %s", buf.String())
}
SetLevel(LevelDebug)
Info(context.Background(), "kept")
if buf.Len() == 0 {
t.Fatal("SetLevel did not lower the level")
}
}
// Dependencies logging through slog.Default must reach the installed logger.
func TestSetGlobalLoggerBridgesSlogDefault(t *testing.T) {
restoreGlobal(t)
buf := new(bytes.Buffer)
SetGlobalLogger(slog.New(newLoggerHandler(LevelDebug, false, buf)))
slog.Info("from a dependency")
if !strings.Contains(buf.String(), "from a dependency") {
t.Fatalf("slog.Default was not bridged: %q", buf.String())
}
}
// A nil logger in the context must fall back to the global logger.
func TestWithLoggerNilFallsBack(t *testing.T) {
Info(WithLogger(context.Background(), nil), "hello")
}
func TestSetGlobalLoggerConcurrent(t *testing.T) {
restoreGlobal(t)
SetGlobalLogger(NewDiscardLogger())
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for range 100 {
SetGlobalLogger(NewDiscardLogger())
}
}()
go func() {
defer wg.Done()
for range 100 {
Info(context.Background(), "concurrent")
}
}()
wg.Wait()
SetGlobalLogger(nil)
if globalLogger.Load() == nil {
t.Fatal("SetGlobalLogger(nil) must not clear the global logger")
}
}
func restoreGlobal(t *testing.T) {
t.Helper()
logger, level, def := globalLogger.Load(), globalLevel.Level(), slog.Default()
t.Cleanup(func() {
globalLogger.Store(logger)
globalLevel.Set(level)
slog.SetDefault(def)
})
}