|
4 | 4 | // Please see LICENSE in the repository root for full details.
|
5 | 5 |
|
6 | 6 | use console::{Color, Style};
|
7 |
| -use opentelemetry::{TraceId, trace::TraceContextExt}; |
| 7 | +use opentelemetry::{ |
| 8 | + TraceId, |
| 9 | + trace::{SamplingDecision, TraceContextExt}, |
| 10 | +}; |
8 | 11 | use tracing::{Level, Subscriber};
|
9 | 12 | use tracing_opentelemetry::OtelData;
|
10 | 13 | use tracing_subscriber::{
|
@@ -128,18 +131,29 @@ where
|
128 | 131 | // If we have a OTEL span, we can add the trace ID to the end of the log line
|
129 | 132 | if let Some(span) = ctx.lookup_current() {
|
130 | 133 | 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 |
134 | 140 | .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 | + } |
143 | 157 | }
|
144 | 158 | }
|
145 | 159 | }
|
|
0 commit comments