Skip to content

Commit 9f60144

Browse files
committed
feat: make trace ID and span ID public on OtelData
1 parent 4ebae2c commit 9f60144

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/lib.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,17 +126,48 @@ 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`).
146+
///
147+
/// [`context`]: OpenTelemetrySpanExt::context
148+
pub fn trace_id(&self) -> Option<opentelemetry::TraceId> {
149+
if let OtelDataState::Context { current_cx } = &self.state {
150+
Some(current_cx.span().span_context().trace_id())
151+
} else {
152+
None
153+
}
154+
}
155+
156+
/// Gets the span ID of the span.
157+
///
158+
/// Returns `None` if the context has not been built yet. This can be forced e.g. by calling
159+
/// [`context`] on the span (not on `OtelData`).
160+
///
161+
/// [`context`]: OpenTelemetrySpanExt::context
162+
pub fn span_id(&self) -> Option<opentelemetry::SpanId> {
163+
if let OtelDataState::Context { current_cx } = &self.state {
164+
Some(current_cx.span().span_context().span_id())
165+
} else {
166+
None
167+
}
168+
}
169+
}
170+
140171
/// The state of the OpenTelemetry data for a span.
141172
#[derive(Debug)]
142173
#[allow(clippy::large_enum_variant)]

0 commit comments

Comments
 (0)