-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcorrelate.go
More file actions
35 lines (28 loc) · 996 Bytes
/
Copy pathcorrelate.go
File metadata and controls
35 lines (28 loc) · 996 Bytes
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
package telemetry
import (
"context"
"encoding/binary"
"log/slog"
// OpenTelemetry
"go.opentelemetry.io/otel/trace"
)
// CorrelateLogsAndTraces returns a logger enriched with trace and span IDs from the context.
// It extracts OpenTelemetry trace and span IDs and adds them as structured log fields,
// including DataDog-compatible decimal representations for correlation.
func CorrelateLogsAndTraces(ctx context.Context, log *slog.Logger) *slog.Logger {
if log == nil {
log = slog.Default()
}
// Get the trace/span IDs from the context:
traceID := trace.SpanContextFromContext(ctx).TraceID()
spanID := trace.SpanContextFromContext(ctx).SpanID()
// DataDog expects 64-bit IDs in decimal, so you might do something like:
ddTraceID := binary.BigEndian.Uint64(traceID[8:16]) // last 8 bytes
ddSpanId := binary.BigEndian.Uint64(spanID[:])
return log.With(
"trace_id", traceID.String(),
"span_id", spanID.String(),
"dd.trace_id", ddTraceID,
"dd.span_id", ddSpanId,
)
}