-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
69 lines (55 loc) · 1.27 KB
/
context.go
File metadata and controls
69 lines (55 loc) · 1.27 KB
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
package supervisor
import (
"context"
"log/slog"
)
type ctxKey string
const (
ctxKeyAttributes ctxKey = "attributes"
ctxKeyChildName ctxKey = "group.name"
)
type attributes struct {
values map[string][]slog.Attr
}
func (a attributes) Set(key string, attr slog.Attr) {
values, ok := a.values[key]
if !ok {
values = []slog.Attr{attr}
} else {
values = append(values, attr)
}
a.values[key] = values
}
func newAttributes() attributes {
return attributes{
values: map[string][]slog.Attr{},
}
}
type ContextSupervisor struct {
slog.Handler
}
func (h ContextSupervisor) Handle(ctx context.Context, r slog.Record) {
h.Handler.Handle(ctx, r)
}
func contextAttributes(ctx context.Context) (attributes, bool) {
v, ok := ctx.Value(ctxKeyAttributes).(attributes)
return v, ok
}
func contextInit(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxKeyAttributes, newAttributes())
}
func NewChild(ctx context.Context, name string) context.Context {
_, ok := contextAttributes(ctx)
if !ok {
ctx = contextInit(ctx)
}
ctx = context.WithValue(ctx, ctxKeyChildName, name)
return ctx
}
func ContextAddAttributes(ctx context.Context, attr slog.Attr) {
attrs, ok := contextAttributes(ctx)
if !ok {
attrs = newAttributes()
}
attrs.Set(attr.Key, attr)
}