-
Notifications
You must be signed in to change notification settings - Fork 0
/
slog.go
55 lines (43 loc) · 1.17 KB
/
slog.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
package s10s
import (
"context"
"log/slog"
)
type discardHandler struct {
slog.JSONHandler
}
func (d *discardHandler) Enabled(context.Context, slog.Level) bool { return false }
type ctxKey string
const (
slogFields ctxKey = "slog_fields"
)
func NewContextHandler(h slog.Handler) ContextHandler {
return ContextHandler{h}
}
type ContextHandler struct {
slog.Handler
}
// Handle adds contextual attributes to the Record before calling the underlying
// handler
func (h ContextHandler) Handle(ctx context.Context, r slog.Record) error {
if attrs, ok := ctx.Value(slogFields).([]slog.Attr); ok {
for _, v := range attrs {
r.AddAttrs(v)
}
}
return h.Handler.Handle(ctx, r)
}
// AppendCtx adds an slog attribute to the provided context so that it will be
// included in any Record created with such context
func AppendCtx(parent context.Context, attrs ...slog.Attr) context.Context {
if parent == nil {
parent = context.Background()
}
if v, ok := parent.Value(slogFields).([]slog.Attr); ok {
v = append(v, attrs...)
return context.WithValue(parent, slogFields, v)
}
v := []slog.Attr{}
v = append(v, attrs...)
return context.WithValue(parent, slogFields, v)
}