-
Notifications
You must be signed in to change notification settings - Fork 413
/
slog_test.go
99 lines (88 loc) · 2.4 KB
/
slog_test.go
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
package watermill
import (
"bytes"
"errors"
"strings"
"testing"
"log/slog"
"github.com/stretchr/testify/assert"
)
func TestSlogLoggerAdapter(t *testing.T) {
b := &bytes.Buffer{}
logger := NewSlogLogger(slog.New(slog.NewTextHandler(
b, // output
&slog.HandlerOptions{
Level: LevelTrace,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "time" && len(groups) == 0 {
// omit time stamp to make the test idempotent
a.Value = slog.StringValue("[omit]")
}
return a
},
},
)))
logger = logger.With(LogFields{
"common1": "commonvalue",
})
logger.Trace("test trace", LogFields{
"field1": "value1",
})
logger.Error("test error", errors.New("error message"), LogFields{
"field2": "value2",
})
logger.Info("test info", LogFields{
"field3": "value3",
})
assert.Equal(t,
strings.TrimSpace(`
time=[omit] level=DEBUG-4 msg="test trace" common1=commonvalue field1=value1
time=[omit] level=ERROR msg="test error" common1=commonvalue field2=value2 error="error message"
time=[omit] level=INFO msg="test info" common1=commonvalue field3=value3
`),
strings.TrimSpace(b.String()),
"Logging output does not match saved template.",
)
}
func TestSlogLoggerAdapter_level_mapping(t *testing.T) {
b := &bytes.Buffer{}
logger := NewSlogLoggerWithLevelMapping(
slog.New(slog.NewTextHandler(
b, // output
&slog.HandlerOptions{
Level: LevelTrace,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "time" && len(groups) == 0 {
// omit time stamp to make the test idempotent
a.Value = slog.StringValue("[omit]")
}
return a
},
},
)),
map[slog.Level]slog.Level{
slog.LevelInfo: slog.LevelDebug,
},
)
logger = logger.With(LogFields{
"common1": "commonvalue",
})
logger.Trace("test trace", LogFields{
"field1": "value1",
})
logger.Error("test error", errors.New("error message"), LogFields{
"field2": "value2",
})
logger.Info("test info mapped to debug", LogFields{
"field3": "value3",
})
assert.Equal(t,
strings.TrimSpace(`
time=[omit] level=DEBUG-4 msg="test trace" common1=commonvalue field1=value1
time=[omit] level=ERROR msg="test error" common1=commonvalue field2=value2 error="error message"
time=[omit] level=DEBUG msg="test info mapped to debug" common1=commonvalue field3=value3
`),
strings.TrimSpace(b.String()),
"Logging output does not match saved template.",
)
}