-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhandler.go
88 lines (72 loc) · 2.07 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
86
87
88
package slogformatter
import (
"context"
"log/slog"
)
var _ slog.Handler = (*FormatterHandler)(nil)
type FormatterHandler struct {
groups []string
formatters []Formatter
handler slog.Handler
}
// NewFormatterHandler returns a slog.Handler that applies formatters to.
func NewFormatterHandler(formatters ...Formatter) func(slog.Handler) slog.Handler {
return func(handler slog.Handler) slog.Handler {
return &FormatterHandler{
groups: []string{},
formatters: formatters,
handler: handler,
}
}
}
// Enabled implements slog.Handler.
func (h *FormatterHandler) Enabled(ctx context.Context, l slog.Level) bool {
return h.handler.Enabled(ctx, l)
}
// Handle implements slog.Handler.
func (h *FormatterHandler) Handle(ctx context.Context, r slog.Record) error {
r2 := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
r.Attrs(func(attr slog.Attr) bool {
r2.AddAttrs(h.transformAttr(h.groups, attr))
return true
})
return h.handler.Handle(ctx, r2)
}
// WithAttrs implements slog.Handler.
func (h *FormatterHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
attrs = h.transformAttrs(h.groups, attrs)
return &FormatterHandler{
groups: h.groups,
formatters: h.formatters,
handler: h.handler.WithAttrs(attrs),
}
}
// WithGroup implements slog.Handler.
func (h *FormatterHandler) WithGroup(name string) slog.Handler {
// https://cs.opensource.google/go/x/exp/+/46b07846:slog/handler.go;l=247
if name == "" {
return h
}
return &FormatterHandler{
groups: append(h.groups, name),
formatters: h.formatters,
handler: h.handler.WithGroup(name),
}
}
func (h *FormatterHandler) transformAttrs(groups []string, attrs []slog.Attr) []slog.Attr {
for i := range attrs {
attrs[i] = h.transformAttr(groups, attrs[i])
}
return attrs
}
func (h *FormatterHandler) transformAttr(groups []string, attr slog.Attr) slog.Attr {
for attr.Value.Kind() == slog.KindLogValuer {
attr.Value = attr.Value.LogValuer().LogValue()
}
for _, formatter := range h.formatters {
if v, ok := formatter(groups, attr); ok {
attr.Value = v
}
}
return attr
}