Tracer trait is the interface for constructing spans. Tracers are responsible for creating new spans and managing the active span context.
Tracer Interface
The coreTracer 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, useInstrumentationScope to provide version and schema information:
Creating Spans
Simple Span Creation
Thestart method creates a span with the current context as its parent:
Explicit Parent Context
Usestart_with_context to specify the parent context:
Using SpanBuilder
For advanced span configuration, useSpanBuilder:
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
TheSpanBuilder 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
Correct Async Pattern
Why Guards Don’t Work in Async
Fromopentelemetry/src/trace/tracer.rs:79-95:
_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 fromexamples/tracing-grpc/src/client.rs:41-84:
Best Practices
Use meaningful span names
Use meaningful span names
Span names should be general enough to group similar operations but specific enough to be useful. Use
get_user instead of get_user/314159.Prefer in_span over manual management
Prefer in_span over manual management
The
in_span method handles activation and cleanup automatically, reducing the risk of leaking spans or incorrect parent relationships.Include version information
Include version information
Always provide version information when instrumenting libraries to help with debugging and understanding trace data.
Set appropriate SpanKind
Set appropriate SpanKind
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