-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtracing_handler.go
61 lines (52 loc) · 1.73 KB
/
tracing_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
package slogsimple
import (
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"golang.org/x/exp/slog"
)
const TraceIDKey = "trace_id"
type TracingHandler struct {
handler slog.Handler
}
func NewTracingHandler(h slog.Handler) *TracingHandler {
// avoid chains of TracingHandlers.
if lh, ok := h.(*TracingHandler); ok {
h = lh.Handler()
}
return &TracingHandler{h}
}
// Enabled implements Handler.Enabled by reporting whether
// level is at least as large as h's level.
func (h *TracingHandler) Enabled(level slog.Level) bool {
return h.handler.Enabled(level)
}
// Handle implements Handler.Handle.
func (h *TracingHandler) Handle(r slog.Record) error {
span := trace.SpanFromContext(r.Context)
if span.IsRecording() {
if r.Level >= slog.LevelError {
span.SetStatus(codes.Error, r.Message)
}
if spanCtx := span.SpanContext(); spanCtx.HasTraceID() {
// With() lost attrs bug has been fixed
// see https://github.com/golang/go/discussions/54763#discussioncomment-4504780
// and https://go.dev/cl/459615
r.AddAttrs(slog.String(TraceIDKey, spanCtx.TraceID().String()))
// do NOT using h.handler = h.handler.WithAttrs, will get duplicated trace_id
// h.handler = h.handler.WithAttrs([]slog.Attr{slog.String(TraceIDKey, traceID)})
}
}
return h.handler.Handle(r)
}
// WithAttrs implements Handler.WithAttrs.
func (h *TracingHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return NewTracingHandler(h.handler.WithAttrs(attrs))
}
// WithGroup implements Handler.WithGroup.
func (h *TracingHandler) WithGroup(name string) slog.Handler {
return NewTracingHandler(h.handler.WithGroup(name))
}
// Handler returns the Handler wrapped by h.
func (h *TracingHandler) Handler() slog.Handler {
return h.handler
}