Skip to content

Commit ac5f4b9

Browse files
committed
Log the trace ID in the log line only if the span is sampled
1 parent 14b0de7 commit ac5f4b9

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

crates/context/src/fmt.rs

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
// Please see LICENSE in the repository root for full details.
55

66
use console::{Color, Style};
7-
use opentelemetry::{TraceId, trace::TraceContextExt};
7+
use opentelemetry::{
8+
TraceId,
9+
trace::{SamplingDecision, TraceContextExt},
10+
};
811
use tracing::{Level, Subscriber};
912
use tracing_opentelemetry::OtelData;
1013
use tracing_subscriber::{
@@ -128,18 +131,29 @@ where
128131
// If we have a OTEL span, we can add the trace ID to the end of the log line
129132
if let Some(span) = ctx.lookup_current() {
130133
if let Some(otel) = span.extensions().get::<OtelData>() {
131-
// If it is the root span, the trace ID will be in the span builder. Else, it
132-
// will be in the parent OTEL context
133-
let trace_id = otel
134+
let parent_cx_span = otel.parent_cx.span();
135+
let sc = parent_cx_span.span_context();
136+
137+
// Check if the span is sampled, first from the span builder,
138+
// then from the parent context if nothing is set there
139+
if otel
134140
.builder
135-
.trace_id
136-
.unwrap_or_else(|| otel.parent_cx.span().span_context().trace_id());
137-
if trace_id != TraceId::INVALID {
138-
let label = Style::new()
139-
.italic()
140-
.force_styling(ansi)
141-
.apply_to("trace.id");
142-
write!(&mut writer, " {label}={trace_id}")?;
141+
.sampling_result
142+
.as_ref()
143+
.map_or(sc.is_sampled(), |r| {
144+
r.decision == SamplingDecision::RecordAndSample
145+
})
146+
{
147+
// If it is the root span, the trace ID will be in the span builder. Else, it
148+
// will be in the parent OTEL context
149+
let trace_id = otel.builder.trace_id.unwrap_or(sc.trace_id());
150+
if trace_id != TraceId::INVALID {
151+
let label = Style::new()
152+
.italic()
153+
.force_styling(ansi)
154+
.apply_to("trace.id");
155+
write!(&mut writer, " {label}={trace_id}")?;
156+
}
143157
}
144158
}
145159
}

0 commit comments

Comments
 (0)