-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
converter_test.go
98 lines (88 loc) · 2.29 KB
/
converter_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
package slogdatadog
import (
"log/slog"
"reflect"
"testing"
"time"
)
var testLogTime = time.Now()
func TestDefaultConverter(t *testing.T) {
type ExampleStruct struct {
ExampleField1 string
ExampleField2 string
}
type args struct {
addSource bool
replaceAttr func(groups []string, a slog.Attr) slog.Attr
loggerAttr []slog.Attr
groups []string
record *slog.Record
}
type testCase struct {
args args
expected map[string]any
}
cases := []testCase{
// Struct values are passed through unstringified.
{
args: args{
false,
dontReplaceAnyAttrs,
[]slog.Attr{
{Key: "Attr1", Value: slog.StringValue("foo")},
{Key: "Attr2", Value: slog.Float64Value(888.88)},
{Key: "Attr3", Value: slog.AnyValue(ExampleStruct{"foo", "bar"})},
},
nil,
&slog.Record{Message: "test", Time: testLogTime},
},
expected: map[string]any{
"level": "INFO",
"Attr1": "foo",
"Attr2": 888.88,
"Attr3": ExampleStruct{"foo", "bar"},
"message": "test",
},
},
// replaceAttr function is called and replaces attributes
{
args: args{
false,
replaceAttrValueWith("Attr1", "baz"),
[]slog.Attr{{Key: "Attr1", Value: slog.StringValue("foo")},
{Key: "Attr2", Value: slog.AnyValue(ExampleStruct{"foo", "bar"})}},
nil,
&slog.Record{Message: "test", Time: testLogTime},
},
expected: map[string]any{
"level": "INFO",
"Attr1": "baz",
"Attr2": ExampleStruct{"foo", "bar"},
"message": "test",
},
},
}
for _, c := range cases {
r := DefaultConverter(c.args.addSource, c.args.replaceAttr, c.args.loggerAttr, c.args.groups, c.args.record)
addCommonExpectedAttrs(c.expected)
if !reflect.DeepEqual(r, c.expected) {
t.Errorf("Expected\n %+v\nGot\n %+v\n", c.expected, r)
}
}
}
func addCommonExpectedAttrs(m map[string]any) {
m["@timestamp"] = testLogTime.UTC()
m["logger.name"] = "samber/slog-datadog"
m["logger.version"] = "VERSION" // won't be replaced in test build
}
func replaceAttrValueWith(name, replacement string) func(groups []string, a slog.Attr) slog.Attr {
return func(groups []string, a slog.Attr) slog.Attr {
if a.Key == name {
a.Value = slog.StringValue(replacement)
}
return a
}
}
func dontReplaceAnyAttrs(groups []string, a slog.Attr) slog.Attr {
return a
}