-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
74 lines (59 loc) · 1.67 KB
/
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
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
// Package otelslog provides an [slog.Handler] that attaches OpenTelemetry trace details to logs.
package otelslog
import (
"context"
"errors"
"log/slog"
"go.opentelemetry.io/otel/trace"
)
const (
traceIDKey = "trace_id"
spanIDKey = "span_id"
)
// NewHandler returns a new [Handler].
func NewHandler(handler slog.Handler) slog.Handler {
return Handler{
Handler: handler,
}
}
// Middleware returns a [Middleware] for an [slogmulti.Pipe] handler.
//
// [Middleware]: https://pkg.go.dev/github.com/samber/slog-multi#Middleware
// [slogmulti.Pipe]: https://pkg.go.dev/github.com/samber/slog-multi#Pipe
func Middleware() func(slog.Handler) slog.Handler {
return func(handler slog.Handler) slog.Handler {
return NewHandler(handler)
}
}
// Handler attaches details from an OpenTelemetry trace to each log record.
type Handler struct {
slog.Handler
}
// Handle implements [slog.Handler].
func (h Handler) Handle(ctx context.Context, record slog.Record) error {
if h.Handler == nil {
return errors.New("otelslog: handler is missing")
}
spanCtx := trace.SpanContextFromContext(ctx)
if spanCtx.HasTraceID() {
record.AddAttrs(slog.String(traceIDKey, spanCtx.TraceID().String()))
}
if spanCtx.HasSpanID() {
record.AddAttrs(slog.String(spanIDKey, spanCtx.SpanID().String()))
}
return h.Handler.Handle(ctx, record)
}
// WithAttrs implements [slog.Handler].
func (h Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
if h.Handler == nil {
return h
}
return Handler{h.Handler.WithAttrs(attrs)}
}
// WithGroup implements [slog.Handler].
func (h Handler) WithGroup(name string) slog.Handler {
if h.Handler == nil {
return h
}
return Handler{h.Handler.WithGroup(name)}
}