-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
76 lines (65 loc) · 1.86 KB
/
Copy pathhandler.go
File metadata and controls
76 lines (65 loc) · 1.86 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
70
71
72
73
74
75
76
package otel
import (
"context"
"errors"
"log/slog"
"go.opentelemetry.io/otel/trace"
)
// TraceHandler wraps an slog.Handler and injects trace_id and span_id
// into each log record when an active OTel span is present in ctx.
type TraceHandler struct {
slog.Handler
}
func (h *TraceHandler) Handle(ctx context.Context, r slog.Record) error {
if sc := trace.SpanFromContext(ctx).SpanContext(); sc.IsValid() {
r.AddAttrs(
slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()),
)
}
return h.Handler.Handle(ctx, r)
}
func (h *TraceHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &TraceHandler{h.Handler.WithAttrs(attrs)}
}
func (h *TraceHandler) WithGroup(name string) slog.Handler {
return &TraceHandler{h.Handler.WithGroup(name)}
}
// FanoutHandler sends each slog.Record to all inner handlers.
// It supports any number of sinks and propagates errors from each handler.
type FanoutHandler []slog.Handler
func (f FanoutHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, h := range f {
if h.Enabled(ctx, level) {
return true
}
}
return false
}
func (f FanoutHandler) Handle(ctx context.Context, r slog.Record) error {
var errs []error
for _, h := range f {
if h.Enabled(ctx, r.Level) {
// Clone so each handler gets an independent copy of the attribute
// backing array — prevents data races when handlers call AddAttrs.
if err := h.Handle(ctx, r.Clone()); err != nil {
errs = append(errs, err)
}
}
}
return errors.Join(errs...)
}
func (f FanoutHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
out := make(FanoutHandler, len(f))
for i, h := range f {
out[i] = h.WithAttrs(attrs)
}
return out
}
func (f FanoutHandler) WithGroup(name string) slog.Handler {
out := make(FanoutHandler, len(f))
for i, h := range f {
out[i] = h.WithGroup(name)
}
return out
}