The simplest way to get a tracer is through the global provider:
use opentelemetry::global;// Get a tracer with just a namelet tracer = global::tracer("my-component");// Get a tracer with versionlet tracer = global::tracer_with_version( "my-component", env!("CARGO_PKG_VERSION"));
The in_span method automatically manages span activation and cleanup:
use opentelemetry::{global, trace::Tracer};let tracer = global::tracer("my-component");tracer.in_span("operation", |cx| { // Span is active within this closure // Span ends automatically when closure returns // Nested spans work automatically tracer.in_span("sub_operation", |_cx| { // This is a child span });});
use opentelemetry::trace::{Tracer, Span, mark_span_as_active};let tracer = global::tracer("my-component");let span = tracer.start("operation");// Mark as active and get a guardlet _guard = mark_span_as_active(span);// Span is active until guard is dropped
use opentelemetry::{Context, trace::{Tracer, TraceContextExt}};let tracer = global::tracer("my-component");let span = tracer.start("operation");// Create a context containing this spanlet cx = Context::current_with_span(span);// Use this context to create child spanslet child = tracer.start_with_context("child", &cx);
use opentelemetry::trace::{Tracer, SpanKind};let tracer = global::tracer("my-component");// Use in_span_with_builder for full controltracer.in_span_with_builder( tracer.span_builder("http_request") .with_kind(SpanKind::Client), |cx| { // Span is active here let span = cx.span(); span.set_attribute(KeyValue::new("key", "value")); });
use opentelemetry::{Context, trace::FutureExt};let cx = Context::current();let my_future = async { // Async work here};// Attach context to the futuremy_future.with_context(cx).await;
// This will NOT work correctly:async { let _g = mark_span_as_active(span); // The guard stays active for the entire future lifetime, // not just when it's being polled!};
The context guard _g will not exit until the future completes. Since futures can be entered and exited multiple times without completing, the span remains active for as long as the future exists, leading to incorrect traces.