-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimezone_handler_test.go
More file actions
89 lines (78 loc) · 2.06 KB
/
Copy pathtimezone_handler_test.go
File metadata and controls
89 lines (78 loc) · 2.06 KB
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
package logging_test
import (
"bytes"
"encoding/json"
"log/slog"
"regexp"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/castai/logging"
)
func TestTimeZoneHandler(t *testing.T) {
t.Run("converts record time to UTC in text output", func(t *testing.T) {
r := require.New(t)
var buf bytes.Buffer
log := logging.New(
logging.NewTextHandler(logging.TextHandlerConfig{
Level: slog.LevelInfo,
Output: &buf,
}),
logging.NewTimeZoneHandler(time.UTC),
)
log.Info("msg")
r.Regexp(regexp.MustCompile(`time=\S+Z `), buf.String())
})
t.Run("converts record time in JSON output", func(t *testing.T) {
r := require.New(t)
loc, err := time.LoadLocation("Europe/Vilnius")
r.NoError(err)
var buf bytes.Buffer
log := logging.New(
logging.NewJSONHandler(logging.JSONHandlerConfig{
Level: slog.LevelInfo,
Output: &buf,
}),
logging.NewTimeZoneHandler(loc),
)
log.Info("msg")
var m map[string]any
r.NoError(json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &m))
ts, _ := m["time"].(string)
parsed, err := time.Parse(time.RFC3339Nano, ts)
r.NoError(err)
_, wantOffset := time.Now().In(loc).Zone()
_, gotOffset := parsed.Zone()
r.Equal(wantOffset, gotOffset)
})
t.Run("nil location is a no-op", func(t *testing.T) {
r := require.New(t)
var buf bytes.Buffer
log := logging.New(
logging.NewTextHandler(logging.TextHandlerConfig{
Level: slog.LevelInfo,
Output: &buf,
}),
logging.NewTimeZoneHandler(nil),
)
log.Info("msg")
r.Contains(buf.String(), "msg=msg")
})
t.Run("preserves WithGroup and WithAttrs", func(t *testing.T) {
r := require.New(t)
var buf bytes.Buffer
log := logging.New(
logging.NewJSONHandler(logging.JSONHandlerConfig{
Level: slog.LevelInfo,
Output: &buf,
}),
logging.NewTimeZoneHandler(time.UTC),
)
log.WithGroup("g").With("k", "v").Info("msg")
var m map[string]any
r.NoError(json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &m))
g, ok := m["g"].(map[string]any)
r.True(ok, "expected group 'g', got %T", m["g"])
r.Equal("v", g["k"])
})
}