-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbuffer_handler.go
218 lines (184 loc) · 4.3 KB
/
buffer_handler.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package collect
import (
"cmp"
"context"
"fmt"
"log/slog"
"runtime"
"sort"
"sync"
)
// CollectorHandler is a test handler that buffers log entries. This is useful for testing
// of log output.
type CollectorHandler struct {
level slog.Level
addTime bool
addSource bool
addLevel bool
goas []groupOrAttrs
data *data
}
type groupOrAttrs struct {
group string
attrs []slog.Attr
}
// prevent mutex copying
type data struct {
fields []map[string]any
mu sync.RWMutex
}
var _ slog.Handler = (*CollectorHandler)(nil)
// NewTestHandler creates a new BufferHandler.
func NewTestHandler(level slog.Level, addTime, addSource, addLevel bool) *CollectorHandler {
h := &CollectorHandler{
level: level,
addTime: addTime,
addSource: addSource,
addLevel: addLevel,
data: &data{
fields: make([]map[string]any, 0),
mu: sync.RWMutex{},
},
}
return h
}
func (h *CollectorHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level >= h.level
}
func (h *CollectorHandler) add(m map[string]any) {
h.data.mu.Lock()
defer h.data.mu.Unlock()
h.data.fields = append(h.data.fields, m)
}
func (h *CollectorHandler) Handle(ctx context.Context, r slog.Record) error {
m := make(map[string]any)
m[slog.MessageKey] = r.Message
if h.addLevel {
m[slog.LevelKey] = r.Level.String()
}
if h.addTime && !r.Time.IsZero() {
m[slog.TimeKey] = r.Time
}
if r.PC != 0 && h.addSource {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
m[slog.SourceKey] = fmt.Sprintf("%s:%d", f.File, f.Line)
}
var groups []string
for _, goa := range h.goas {
if goa.group != "" {
groups = append(groups, goa.group)
} else {
for _, a := range goa.attrs {
h.appendAttr(a, m, groups)
}
}
}
r.Attrs(func(a slog.Attr) bool {
h.appendAttr(a, m, groups)
return true
})
h.add(m)
return nil
}
func (h *CollectorHandler) appendAttr(a slog.Attr, m map[string]any, g []string) {
a.Value = a.Value.Resolve()
if a.Equal(slog.Attr{}) {
return
}
switch a.Value.Kind() {
case slog.KindGroup:
attrs := a.Value.Group()
if len(attrs) == 0 {
return
}
if a.Key == "" {
for _, ga := range attrs {
h.appendAttr(ga, m, g)
}
}
m[a.Key] = make(map[string]any)
for _, ga := range attrs {
h.appendAttr(ga, m[a.Key].(map[string]any), g)
}
default:
add_p(a, m, g)
}
}
func add_p(a slog.Attr, m map[string]any, g []string) {
if len(g) == 0 {
m[a.Key] = a.Value.Any()
return
}
group := g[0]
if _, ok := m[group]; !ok {
m[group] = make(map[string]any)
}
add_p(a, m[group].(map[string]any), g[1:])
}
func (h *CollectorHandler) withGroupOrAttrs(goa groupOrAttrs) *CollectorHandler {
h2 := *h
h2.goas = make([]groupOrAttrs, len(h.goas)+1)
copy(h2.goas, h.goas)
h2.goas[len(h2.goas)-1] = goa
return &h2
}
func (h *CollectorHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
return h.withGroupOrAttrs(groupOrAttrs{attrs: attrs})
}
func (h *CollectorHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
return h.withGroupOrAttrs(groupOrAttrs{group: name})
}
// Last returns the last entry that was logged or an empty map
func (h *CollectorHandler) Last() map[string]any {
h.data.mu.RLock()
defer h.data.mu.RUnlock()
i := len(h.data.fields) - 1
if i < 0 {
return make(map[string]any)
}
return h.data.fields[i]
}
// All returns all entries that were logged.
func (h *CollectorHandler) All() []map[string]any {
h.data.mu.RLock()
defer h.data.mu.RUnlock()
return h.data.fields
}
// Can be replaced by slices.SortedKeys after Go 1.23+ upgrade
func sortedKeys[K cmp.Ordered, V any](m map[K]V) []K {
keys := make([]K, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
return keys
}
// String returns all records formatted as a string.
func (h *CollectorHandler) String() string {
h.data.mu.RLock()
defer h.data.mu.RUnlock()
var s string
for _, m := range h.data.fields {
var keys []string
for _, k := range sortedKeys(m) {
keys = append(keys, fmt.Sprintf("%s=%v", k, m[k]))
}
s += fmt.Sprintf("%s\n", keys)
}
return s
}
// Reset removes all Entries from this test hook.
func (h *CollectorHandler) Reset() {
h.data.mu.Lock()
defer h.data.mu.Unlock()
h.data.fields = make([]map[string]any, 0)
}