-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
45 lines (37 loc) · 946 Bytes
/
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
package ctxslog
import (
"context"
"log/slog"
)
var _ slog.Handler = Handler{}
type Handler struct {
handler slog.Handler
}
func NewHandler(handler slog.Handler) slog.Handler {
return Handler{
handler: handler,
}
}
// Enabled implements slog.Handler.
func (h Handler) Enabled(ctx context.Context, lvl slog.Level) bool {
return h.handler.Enabled(ctx, lvl)
}
// Handle implements slog.Handler.
func (h Handler) Handle(ctx context.Context, r slog.Record) error {
if sm, ok := ctx.Value(fieldsKey).(*safeMap); ok {
sm.mu.Lock()
for k, v := range sm.fields {
r.AddAttrs(slog.Any(string(k), v))
}
sm.mu.Unlock()
}
return h.handler.Handle(ctx, r)
}
// WithAttrs implements slog.Handler.
func (h Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
return Handler{h.handler.WithAttrs(attrs)}
}
// WithGroup implements slog.Handler.
func (h Handler) WithGroup(name string) slog.Handler {
return h.handler.WithGroup(name)
}