Debian Codegraph @

handler.go

raw symbols SCIP
1 package clog
2
3 import (
4 "context"
5 "log/slog"
6 )
7
8 var (
9 ctxKey = key{}
10 )
11
12 type key struct{}
13 type ctxVal map[string]any
14
15 // With returns a new context with the given values.
16 // Values are expected to be key-value pairs, where the key is a string.
17 // e.g. WithValues(ctx, "foo", "bar", "baz", 1)
18 // If a value already exists, it is overwritten.
19 // If an odd number of arguments are provided, With panics.
20 func WithValues(ctx context.Context, args ...any) context.Context {
21 if len(args)%2 != 0 {
22 panic("non-even number of arguments")
23 }
24
25 values := ctxVal{}
26
27 // Copy existing values
28 for k, v := range get(ctx) {
29 values[k] = v
30 }
31
32 for i := 0; i < len(args); i++ {
33 key, ok := args[i].(string)
34 if !ok {
35 panic("non-string key")
36 }
37 i++
38 if i >= len(args) {
39 break
40 }
41 value := args[i]
42 values[key] = value
43 }
44 return context.WithValue(ctx, ctxKey, values)
45 }
46
47 func get(ctx context.Context) ctxVal {
48 if value, ok := ctx.Value(ctxKey).(ctxVal); ok {
49 return value
50 }
51 return nil
52 }
53
54 // Handler is a slog.Handler that adds context values to the log record.
55 // Values are added via [WithValues].
56 type Handler struct {
57 h slog.Handler
58 }
59
60 // NewHandler configures a new context aware slog handler.
61 // If h is nil, the default slog handler is used.
62 func NewHandler(h slog.Handler) Handler {
63 return Handler{h}
64 }
65
66 func (h Handler) inner() slog.Handler {
67 if h.h == nil {
68 return slog.Default().Handler()
69 }
70 return h.h
71 }
72
73 func (h Handler) Enabled(ctx context.Context, level slog.Level) bool {
74 return h.inner().Enabled(ctx, level)
75 }
76
77 func (h Handler) Handle(ctx context.Context, r slog.Record) error {
78 values := get(ctx)
79 for k, v := range values {
80 r.Add(k, v)
81 }
82 return h.inner().Handle(ctx, r)
83 }
84
85 func (h Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
86 return Handler{h.inner().WithAttrs(attrs)}
87 }
88
89 func (h Handler) WithGroup(name string) slog.Handler {
90 return Handler{h.inner().WithGroup(name)}
91 }