logo
Available on crate feature trace only.
Expand description

API for tracing applications and libraries.

The trace module includes 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. This module implements the OpenTelemetry trace specification.

Getting Started

In application code:

use opentelemetry_api::trace::{Tracer, noop::NoopTracerProvider};
use opentelemetry_api::global;

fn init_tracer() {
    // Swap this no-op provider for your tracing service of choice (jaeger, zipkin, etc)
    let provider = NoopTracerProvider::new();

    // Configure the global `TracerProvider` singleton when your app starts
    // (there is a no-op default if this is not set by your application)
    let _ = global::set_tracer_provider(provider);
}

fn do_something_tracked() {
    // Then you can get a named tracer instance anywhere in your codebase.
    let tracer = global::tracer("my-component");

    tracer.in_span("doing_work", |cx| {
        // Traced app logic here...
    });
}

// in main or other app start
init_tracer();
do_something_tracked();

In library code:

use opentelemetry_api::{global, trace::{Span, Tracer, TracerProvider}};

fn my_library_function() {
    // Use the global tracer provider to get access to the user-specified
    // tracer configuration
    let tracer_provider = global::tracer_provider();

    // Get a tracer for this library
    let tracer = tracer_provider.versioned_tracer(
        "my_name",
        Some(env!("CARGO_PKG_VERSION")),
        None
    );

    // Create spans
    let mut span = tracer.start("doing_work");

    // Do work...

    // End the span
    span.end();
}

Overview

The tracing API consists of a three main traits:

  • TracerProviders are the entry point of the API. They provide access to Tracers.
  • Tracers are types responsible for creating Spans.
  • Spans provide the API to trace an operation.

Working with Async Runtimes

Exporting spans often involves sending data over a network or performing other I/O tasks. OpenTelemetry allows you to schedule these tasks using whichever runtime you area already using such as Tokio or async-std. When using an async runtime it’s best to use the batch span processor where the spans will be sent in batches as opposed to being sent once ended, which often ends up being more efficient.

Managing Active Spans

Spans can be marked as “active” for a given Context, and all newly created spans will automatically be children of the currently active span.

The active span for a given thread can be managed via get_active_span and mark_span_as_active.

use opentelemetry_api::{global, trace::{self, Span, Status, Tracer, TracerProvider}};

fn may_error(rand: f32) {
    if rand < 0.5 {
        // Get the currently active span to record additional attributes,
        // status, etc.
        trace::get_active_span(|span| {
            span.set_status(Status::error("value too small"));
        });
    }
}

// Get a tracer
let tracer = global::tracer("my_tracer");

// Create a span
let span = tracer.start("parent_span");

// Mark the span as active
let active = trace::mark_span_as_active(span);

// Any span created here will be a child of `parent_span`...

// Drop the guard and the span will no longer be active
drop(active)

Additionally Tracer::in_span can be used as shorthand to simplify managing the parent context.

use opentelemetry_api::{global, trace::Tracer};

// Get a tracer
let tracer = global::tracer("my_tracer");

// Use `in_span` to create a new span and mark it as the parent, dropping it
// at the end of the block.
tracer.in_span("parent_span", |cx| {
    // spans created here will be children of `parent_span`
});
Async active spans

Async spans can be propagated with TraceContextExt and FutureExt.

use opentelemetry_api::{Context, global, trace::{FutureExt, TraceContextExt, Tracer}};

async fn some_work() { }

// Get a tracer
let tracer = global::tracer("my_tracer");

// Start a span
let span = tracer.start("my_span");

// Perform some async work with this span as the currently active parent.
some_work().with_context(Context::current_with_span(span));

Modules

No-op trace impls

Structs

Events record things that happened during a Span’s lifetime.

Link is the relationship between two Spans.

A hash table implementation that preserves insertion order across all operations.

The result of sampling logic for a given span.

SpanBuilder allows span attributes to be configured before the span has started.

Immutable portion of a Span which can be serialized and propagated.

An 8-byte value which identifies a given span.

A reference to the currently active span in this context.

Flags that can be set on a SpanContext.

A 16-byte value which identifies a given trace.

TraceState carries system-specific configuration data, represented as a list of key-value pairs. TraceState allows multiple tracing systems to participate in the same trace.

Enums

Decision about whether or not to sample

SpanKind describes the relationship between the Span, its parents, and its children in a trace.

The status of a Span.

Errors returned by the trace API.

Traits

Extension trait allowing futures, streams, and sinks to be traced with a span.

The interface for a single operation within a trace.

Methods for storing and retrieving trace data in a Context.

The interface for constructing Spans.

Types that can create instances of Tracer.

Functions

Executes a closure with a reference to this thread’s current span.

Mark a given Span as active.

Type Definitions

Describe the result of operations in tracing API.