Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion foundations/src/telemetry/tracing/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub(crate) struct SharedSpan {
pub(crate) inner: SharedSpanHandle,
// NOTE: store sampling flag separately, so we don't need to acquire lock
// every time we need to check the flag.
is_sampled: bool,
pub(crate) is_sampled: bool,
}

impl From<Span> for SharedSpan {
Expand Down
10 changes: 9 additions & 1 deletion foundations/src/telemetry/tracing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,9 +232,17 @@ pub struct StartTraceOptions {
pub override_sampling_ratio: Option<f64>,
}

/// Determines whether the current span is sampled or not.
///
/// This is useful to do a cheap check before commencing more expensive work,
/// for example to set up span tags.
pub fn span_is_sampled() -> bool {
matches!(current_span(), Some(span) if span.is_sampled)
}

/// Returns a trace ID of the current span.
///
/// Returns `None` if the span is not sampled and don't have associated trace.
/// Returns `None` if the span is not sampled and doesn't have associated trace.
pub fn trace_id() -> Option<String> {
current_span()?.inner.with_read(span_trace_id)
}
Expand Down
34 changes: 34 additions & 0 deletions foundations/tests/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,37 @@ fn test_passive_sampler(mut ctx: TestTelemetryContext) {

assert_eq!(ctx.traces(Default::default()).len(), 0);
}

#[with_test_telemetry(test)]
fn test_span_accessors(mut ctx: TestTelemetryContext) {
// Initially, no trace (and no span) is present
assert!(!tracing::span_is_sampled());
assert_eq!(tracing::trace_id(), None);

{
// Start a new trace
let _root_scope = tracing::start_trace("my first span", Default::default());
assert!(tracing::span_is_sampled());

let trace_id = tracing::trace_id().expect("root scope should set trace ID");
let trace_state =
tracing::state_for_trace_stitching().expect("root scope should set stitching state");
assert_eq!(trace_state.trace_id().to_string(), trace_id);

// Enter a child span, which should have the same trace ID
let _child_scope = tracing::span("my child span");
assert!(tracing::span_is_sampled());
assert_eq!(tracing::trace_id(), Some(trace_id));
}

// Change to the passive sampler, which won't sample new root traces
ctx.set_tracing_settings(TracingSettings {
sampling_strategy: SamplingStrategy::Passive,
..Default::default()
});
let _ctx_scope = ctx.scope();

let _unsampled_scope = tracing::start_trace("my unsampled span", Default::default());
assert!(!tracing::span_is_sampled());
assert_eq!(tracing::trace_id(), None);
}
Loading