-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrace_extractor.go
More file actions
68 lines (61 loc) · 1.66 KB
/
Copy pathtrace_extractor.go
File metadata and controls
68 lines (61 loc) · 1.66 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
package logging
import (
"context"
"log/slog"
"sync/atomic"
)
// TraceSpanExtractor pulls trace and span IDs out of a context so log
// entries derived via FromContext can be enriched with `trace_id` and
// `span_id` fields.
type TraceSpanExtractor interface {
TraceID(ctx context.Context) string
SpanID(ctx context.Context) string
}
// extractorHolder wraps a TraceSpanExtractor in an atomic.Pointer so
// SetTraceSpanExtractor is safe against concurrent readers on the log path.
type extractorHolder struct {
e TraceSpanExtractor
}
var traceExtractor atomic.Pointer[extractorHolder]
// SetTraceSpanExtractor registers the process-wide extractor. Pass nil to
// disable trace/span attachment.
func SetTraceSpanExtractor(e TraceSpanExtractor) {
if e == nil {
traceExtractor.Store(nil)
return
}
traceExtractor.Store(&extractorHolder{e: e})
}
// getTraceExtractor returns the currently-registered extractor, or nil if
// none is set.
func getTraceExtractor() TraceSpanExtractor {
h := traceExtractor.Load()
if h == nil {
return nil
}
return h.e
}
// attachTraceFields returns a logger derived from l with trace_id and/or
// span_id fields attached.
func attachTraceFields(ctx context.Context, l *Logger) *Logger {
if ctx == nil || l.traceAttached {
return l
}
e := getTraceExtractor()
if e == nil {
return l
}
traceID := e.TraceID(ctx)
spanID := e.SpanID(ctx)
if traceID == "" && spanID == "" {
return l
}
attrs := make([]any, 0, 2)
if traceID != "" {
attrs = append(attrs, slog.String("trace_id", traceID))
}
if spanID != "" {
attrs = append(attrs, slog.String("span_id", spanID))
}
return &Logger{Log: l.Log.With(attrs...), traceAttached: true}
}