Skip to content

Commit 73a6baf

Browse files
authored
feat: make trace ID and span ID public on OtelData (#233)
## Motivation Get the IDs from the `OtelData` struct. Closes #227 ## Solution When the context is started, we can get the IDs. There is however nothing to report when the context is not yet fully built. But if it is not, there is not span ID to report and reporting the parent span's trace ID from the builder may not be correct as that may still change.
1 parent 4ebae2c commit 73a6baf

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

src/lib.rs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,17 +126,52 @@ pub use layer::{layer, OpenTelemetryLayer};
126126

127127
#[cfg(feature = "metrics")]
128128
pub use metrics::MetricsLayer;
129+
use opentelemetry::trace::TraceContextExt as _;
129130
pub use span_ext::OpenTelemetrySpanExt;
130131

131132
/// Per-span OpenTelemetry data tracked by this crate.
132133
#[derive(Debug)]
133-
pub(crate) struct OtelData {
134+
pub struct OtelData {
134135
/// The state of the OtelData, which can either be a builder or a context.
135136
state: OtelDataState,
136137
/// The end time of the span if it has been exited.
137138
end_time: Option<SystemTime>,
138139
}
139140

141+
impl OtelData {
142+
/// Gets the trace ID of the span.
143+
///
144+
/// Returns `None` if the context has not been built yet. This can be forced e.g. by calling
145+
/// [`context`] on the span (not on `OtelData`) or if [context activation] was not explicitly
146+
/// opted-out of, simply entering the span for the first time.
147+
///
148+
/// [`context`]: OpenTelemetrySpanExt::context
149+
/// [context activation]: OpenTelemetryLayer::with_context_activation
150+
pub fn trace_id(&self) -> Option<opentelemetry::TraceId> {
151+
if let OtelDataState::Context { current_cx } = &self.state {
152+
Some(current_cx.span().span_context().trace_id())
153+
} else {
154+
None
155+
}
156+
}
157+
158+
/// Gets the span ID of the span.
159+
///
160+
/// Returns `None` if the context has not been built yet. This can be forced e.g. by calling
161+
/// [`context`] on the span (not on `OtelData`) or if [context activation] was not explicitly
162+
/// opted-out of, simply entering the span for the first time.
163+
///
164+
/// [`context`]: OpenTelemetrySpanExt::context
165+
/// [context activation]: OpenTelemetryLayer::with_context_activation
166+
pub fn span_id(&self) -> Option<opentelemetry::SpanId> {
167+
if let OtelDataState::Context { current_cx } = &self.state {
168+
Some(current_cx.span().span_context().span_id())
169+
} else {
170+
None
171+
}
172+
}
173+
}
174+
140175
/// The state of the OpenTelemetry data for a span.
141176
#[derive(Debug)]
142177
#[allow(clippy::large_enum_variant)]

0 commit comments

Comments
 (0)