Learn about distributed tracing in OpenTelemetry Rust and how to instrument your applications
The trace module provides types for tracking the progression of a single request while it is handled by services that make up an application. A trace is a tree of Spans which are objects that represent the work being done by individual services or components involved in a request as it flows through a system.
Zero or more child spans - Spans that have a parent span
Spans can be nested to form a trace tree:
let tracer = global::tracer("my-tracer");tracer.in_span("parent_operation", |_cx| { // This is the root span tracer.in_span("child_operation", |_cx| { // This is a child span });});
In synchronous code, use in_span for automatic span management:
use opentelemetry::{global, trace::Tracer};let tracer = global::tracer("my-component");tracer.in_span("operation", |_cx| { // Span is active here // Span ends automatically when closure returns});
For async code, use the FutureExt trait to attach context to futures:
use opentelemetry::{trace::FutureExt, Context};let cx = Context::current();let my_future = async { // Async work here};my_future.with_context(cx).await;
Do not use mark_span_as_active directly in async blocks, as the guard will remain active for the entire lifetime of the future, not just when it’s being polled.
OpenTelemetry provides a global TracerProvider singleton:
use opentelemetry::global;// Get a tracer anywhere in your applicationlet tracer = global::tracer("my-component");// Or with version informationlet tracer = global::tracer_with_version( "my-component", env!("CARGO_PKG_VERSION"));