-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
85 lines (69 loc) · 1.63 KB
/
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
package slogtest
import (
"context"
"log/slog"
"slices"
"sync"
"github.com/stretchr/testify/assert"
)
type sharedRecords struct {
mx sync.RWMutex
records []slog.Record
}
func newSharedRecords() *sharedRecords {
return &sharedRecords{}
}
func (r *sharedRecords) Add(record slog.Record) {
r.mx.Lock()
defer r.mx.Unlock()
r.records = append(r.records, record)
}
func (r *sharedRecords) All() []slog.Record {
r.mx.RLock()
defer r.mx.RUnlock()
return r.records
}
type Handler struct {
t assert.TestingT
groups []string
attrs []slog.Attr
recordCallbackF func(record slog.Record)
records *sharedRecords
}
func NewHandler(t assert.TestingT, recordCallbackF func(record slog.Record)) *Handler {
return &Handler{
t: t,
recordCallbackF: recordCallbackF,
records: newSharedRecords(),
}
}
func (h *Handler) Enabled(_ context.Context, _ slog.Level) bool {
return true
}
func (h *Handler) Handle(_ context.Context, record slog.Record) error {
h.recordCallbackF(record)
h.records.Add(record)
return nil
}
func (h *Handler) Records() []slog.Record {
return h.records.All()
}
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
handler := h.clone()
handler.attrs = append(handler.attrs, attrs...)
return handler
}
func (h *Handler) WithGroup(name string) slog.Handler {
handler := h.clone()
handler.groups = append(handler.groups, name)
return handler
}
func (h *Handler) clone() *Handler {
return &Handler{
t: h.t,
groups: slices.Clone(h.groups),
attrs: slices.Clone(h.attrs),
recordCallbackF: h.recordCallbackF,
records: h.records,
}
}