-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathformatter_test.go
106 lines (86 loc) · 2.33 KB
/
formatter_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
106
package slogformatter
import (
"context"
"log/slog"
"sync/atomic"
"testing"
"time"
slogmock "github.com/samber/slog-mock"
"github.com/stretchr/testify/assert"
)
func TestFormatByKind(t *testing.T) {
t.Parallel()
is := assert.New(t)
handler := NewFormatterMiddleware(
FormatByKind(slog.KindDuration, func(v slog.Value) slog.Value {
return slog.StringValue(v.Duration().String())
}),
)
var checked int32
logger := slog.New(
handler(
slogmock.Option{
Handle: func(ctx context.Context, record slog.Record) error {
is.Equal("hello world", record.Message)
attrs := map[string]slog.Value{}
record.Attrs(func(attr slog.Attr) bool {
attrs[attr.Key] = attr.Value
return true
})
is.Len(attrs, 2)
is.Equal(attrs["key"], slog.StringValue("value"))
is.Equal(attrs["subgroup"].Kind(), slog.KindGroup)
is.Equal(attrs["subgroup"].Group()[0].Key, "duration")
is.Equal(attrs["subgroup"].Group()[0].Value, slog.StringValue("1s"))
atomic.AddInt32(&checked, 1)
return nil
},
}.NewMockHandler(),
),
)
logger.Info("hello world",
slog.String("key", "value"),
slog.Group("subgroup",
slog.Duration("duration", 1*time.Second),
),
)
is.Equal(int32(1), atomic.LoadInt32(&checked))
}
func TestFormatByKey(t *testing.T) {
t.Parallel()
is := assert.New(t)
handler := NewFormatterMiddleware(
FormatByKey("duration", func(v slog.Value) slog.Value {
return slog.StringValue(v.Duration().String())
}),
)
var checked int32
logger := slog.New(
handler(
slogmock.Option{
Handle: func(ctx context.Context, record slog.Record) error {
is.Equal("hello world", record.Message)
attrs := map[string]slog.Value{}
record.Attrs(func(attr slog.Attr) bool {
attrs[attr.Key] = attr.Value
return true
})
is.Len(attrs, 2)
is.Equal(attrs["key"], slog.StringValue("value"))
is.Equal(attrs["subgroup"].Kind(), slog.KindGroup)
is.Equal(attrs["subgroup"].Group()[0].Key, "duration")
is.Equal(attrs["subgroup"].Group()[0].Value, slog.StringValue("1s"))
atomic.AddInt32(&checked, 1)
return nil
},
}.NewMockHandler(),
),
)
logger.Info("hello world",
slog.String("key", "value"),
slog.Group("subgroup",
slog.Duration("duration", 1*time.Second),
),
)
is.Equal(int32(1), atomic.LoadInt32(&checked))
}