Skip to main content
The Tracer trait is the interface for constructing spans. Tracers are responsible for creating new spans and managing the active span context.

Tracer Interface

The core Tracer trait is defined in opentelemetry/src/trace/tracer.rs:121:

Getting a Tracer

Using the Global TracerProvider

The simplest way to get a tracer is through the global provider:

Using InstrumentationScope

For library instrumentation, use InstrumentationScope to provide version and schema information:

Creating Spans

Simple Span Creation

The start method creates a span with the current context as its parent:

Explicit Parent Context

Use start_with_context to specify the parent context:

Using SpanBuilder

For advanced span configuration, use SpanBuilder:

Active Span Management

Using in_span

The in_span method automatically manages span activation and cleanup:

Manual Span Activation

For more control, manually activate spans:

Accessing the Active Span

Get a reference to the currently active span:

Advanced Configuration with SpanBuilder

The SpanBuilder struct (defined in opentelemetry/src/trace/tracer.rs:356) provides full control over span creation:

Builder Methods

Working with Context

Creating Context with Spans

Using Contexts with in_span

Async/Await Support

The standard span activation methods do not work correctly with async/await. Use FutureExt instead.

Correct Async Pattern

Why Guards Don’t Work in Async

From opentelemetry/src/trace/tracer.rs:79-95:
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.

Real-World Example

Here’s a complete example from examples/tracing-grpc/src/client.rs:41-84:

Best Practices

Span names should be general enough to group similar operations but specific enough to be useful. Use get_user instead of get_user/314159.
The in_span method handles activation and cleanup automatically, reducing the risk of leaking spans or incorrect parent relationships.
Always provide version information when instrumenting libraries to help with debugging and understanding trace data.
Use the correct SpanKind (Client, Server, Internal, Producer, Consumer) to help tracing backends understand the relationships between spans.

Next Steps

Spans

Learn about span lifecycle, attributes, and events

Context

Understand context propagation