-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
67 lines (57 loc) · 1.67 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
package meld
import (
"context"
"log/slog"
"snqk.dev/slog/meld/internal/tree"
)
type handler struct {
next slog.Handler
stack []string
root *tree.Group
}
// NewHandler returns a slog.Handler which melds (joins) older slog.Attr(s) with newer updates, making it a mutable slog.Handler.
// It is thread-safe by immutability; handler state is never updated in-place after creation.
// It is recursive; merging slog.KindGroup, and replacing / updating all other types as appropriate.
// It is ordered; slog.Attr(s) configured first will appear in order. Replacing an attribute does not change its position in the order.
func NewHandler(next slog.Handler) slog.Handler {
return &handler{
next: next,
stack: nil,
root: new(tree.Group),
}
}
func (h *handler) Enabled(ctx context.Context, level slog.Level) bool {
return h.next.Enabled(ctx, level)
}
func (h *handler) Handle(ctx context.Context, rec slog.Record) error {
newRec := slog.NewRecord(rec.Time, rec.Level, rec.Message, rec.PC)
if rec.NumAttrs() == 0 { // optimisation
newRec.AddAttrs(h.root.Render()...)
} else {
newRoot := h.root.Clone()
rec.Attrs(func(attr slog.Attr) bool {
newRoot.Merge(h.stack, attr)
return true
})
newRec.AddAttrs(newRoot.Render()...)
}
return h.next.Handle(ctx, newRec)
}
func (h *handler) WithAttrs(attrs []slog.Attr) slog.Handler {
newRoot := h.root.Clone()
newRoot.Merge(h.stack, attrs...)
return &handler{
next: h.next,
stack: h.stack,
root: newRoot,
}
}
func (h *handler) WithGroup(name string) slog.Handler {
newRoot := h.root.Clone()
newRoot.Merge(h.stack, slog.Group(name))
return &handler{
next: h.next,
stack: append(h.stack, name),
root: newRoot,
}
}