forked from rs/zerolog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx_test.go
101 lines (83 loc) · 2.3 KB
/
ctx_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
package zerolog
import (
"bytes"
"context"
"io"
"reflect"
"testing"
"github.com/rs/zerolog/internal/cbor"
)
func TestCtx(t *testing.T) {
log := New(io.Discard)
ctx := log.WithContext(context.Background())
log2 := Ctx(ctx)
if !reflect.DeepEqual(log, *log2) {
t.Error("Ctx did not return the expected logger")
}
// update
log = log.Level(InfoLevel)
ctx = log.WithContext(ctx)
log2 = Ctx(ctx)
if !reflect.DeepEqual(log, *log2) {
t.Error("Ctx did not return the expected logger")
}
log2 = Ctx(context.Background())
if log2 != disabledLogger {
t.Error("Ctx did not return the expected logger")
}
DefaultContextLogger = &log
t.Cleanup(func() { DefaultContextLogger = nil })
log2 = Ctx(context.Background())
if log2 != &log {
t.Error("Ctx did not return the expected logger")
}
}
func TestCtxDisabled(t *testing.T) {
dl := New(io.Discard).Level(Disabled)
ctx := dl.WithContext(context.Background())
if ctx != context.Background() {
t.Error("WithContext stored a disabled logger")
}
l := New(io.Discard).With().Str("foo", "bar").Logger()
ctx = l.WithContext(ctx)
if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store logger")
}
l.UpdateContext(func(c Context) Context {
return c.Str("bar", "baz")
})
ctx = l.WithContext(ctx)
if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store updated logger")
}
l = l.Level(DebugLevel)
ctx = l.WithContext(ctx)
if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store copied logger")
}
ctx = dl.WithContext(ctx)
if !reflect.DeepEqual(Ctx(ctx), &dl) {
t.Error("WithContext did not override logger with a disabled logger")
}
}
type logObjectMarshalerImpl struct {
name string
age int
}
func (t logObjectMarshalerImpl) MarshalZerologObject(e *Event) {
e.Str("name", "custom_value").Int("age", t.age)
}
func Test_InterfaceLogObjectMarshaler(t *testing.T) {
var buf bytes.Buffer
log := New(&buf)
ctx := log.WithContext(context.Background())
log2 := Ctx(ctx)
withLog := log2.With().Interface("obj", &logObjectMarshalerImpl{
name: "foo",
age: 29,
}).Logger()
withLog.Info().Msg("test")
if got, want := cbor.DecodeIfBinaryToString(buf.Bytes()), `{"level":"info","obj":{"name":"custom_value","age":29},"message":"test"}`+"\n"; got != want {
t.Errorf("got %q, want %q", got, want)
}
}