-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlog_test.go
105 lines (88 loc) · 2.22 KB
/
log_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
100
101
102
103
104
105
package logging
import (
"bytes"
"context"
"testing"
"github.com/DoNewsCode/core/ctxmeta"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/stretchr/testify/assert"
)
func TestWithLevel(t *testing.T) {
var buf bytes.Buffer
l := log.NewLogfmtLogger(&buf)
ll := WithLevel(l)
ll.Debug("hi")
// ensure the caller depth is correct
assert.Contains(t, buf.String(), "caller=log_test.go")
assert.Contains(t, buf.String(), "level=debug")
ll.Debugw("foo", "bar", "baz")
assert.Contains(t, buf.String(), "bar=baz")
ll.Debugf("foo%d", 1)
assert.Contains(t, buf.String(), "foo1")
}
func TestLevelFilter(t *testing.T) {
var buf bytes.Buffer
l := log.NewLogfmtLogger(&buf)
l = level.NewFilter(l, LevelFilter("error"))
WithLevel(l).Debug("hi")
// ensure the caller depth is correct
assert.NotContains(t, buf.String(), "caller=log_test.go")
}
func TestNewLogger(t *testing.T) {
_ = NewLogger("logfmt")
}
func TestWithContext(t *testing.T) {
ctx := context.Background()
bag, ctx := ctxmeta.Inject(ctx)
bag.Set("foo", "bar")
var buf bytes.Buffer
l := log.NewLogfmtLogger(&buf)
ll := WithContext(l, ctx)
ll.Log("baz", "qux")
assert.Contains(t, buf.String(), "foo=bar baz=qux")
}
type mockSpan struct {
received []any
}
func (m *mockSpan) LogKV(alternatingKeyValues ...any) {
m.received = alternatingKeyValues
}
func TestSpanLogger(t *testing.T) {
var mock mockSpan
spanLogger{
span: &mock,
base: log.NewNopLogger(),
kvs: []any{"foo", log.Valuer(func() any { return "bar" })},
}.Log("baz", "qux")
assert.Equal(t, []any{"foo", "bar", "baz", "qux"}, mock.received)
}
type mockValue struct{}
func (m mockValue) String() string {
// potentially expensive, but the cost is avoided because we have set a higher log level.
panic("should not reach here")
}
func TestPerformanceOptimization(t *testing.T) {
var buf bytes.Buffer
for _, c := range []struct {
name string
logger log.Logger
}{
{
"json",
log.NewJSONLogger(&buf),
},
{
"logfmt",
log.NewLogfmtLogger(&buf),
},
} {
t.Run(c.name, func(t *testing.T) {
l := level.NewFilter(c.logger, LevelFilter("error"))
ll := WithLevel(l)
ll.Debug(mockValue{})
ll.Debugw("bar", "foo", mockValue{})
ll.Debugf("%s", mockValue{})
})
}
}