Skip to main content

Module otel

Module otel 

Source
Expand description

OpenTelemetry-compatible distributed tracing.

OtelLayer is a Middleware that:

  1. Reads the W3C traceparent header from incoming requests and continues an existing trace, or starts a fresh one.
  2. Creates an HTTP server span with standard semantic attributes.
  3. Stores the active span context in thread-local storage so downstream middleware (e.g. crate::proxy::ReverseProxy) can propagate it.
  4. Records the completed span to a configurable exporter.

§Quick start

use rust_web_server::app::App;
use rust_web_server::core::New;
use rust_web_server::otel::{OtelLayer, TracingConfig, ExporterConfig};

// Dev: print spans to stdout.
rust_web_server::otel::setup(TracingConfig {
    service_name: "my-service".to_string(),
    service_version: env!("CARGO_PKG_VERSION").to_string(),
    exporter: ExporterConfig::Stdout,
    sample_rate: 1.0,
    batch_size: 128,
});

let app = App::new().wrap(OtelLayer);

§Production: OTLP HTTP export

use rust_web_server::otel::{ExporterConfig, TracingConfig};

rust_web_server::otel::setup(TracingConfig {
    service_name: "my-service".to_string(),
    service_version: "1.0.0".to_string(),
    exporter: ExporterConfig::Otlp {
        endpoint: "http://localhost:4318".to_string(),
    },
    sample_rate: 0.1,
    batch_size: 512,
});

Alternatively, set environment variables before calling setup_from_env:

OTEL_SERVICE_NAME=my-service
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_TRACES_SAMPLER_ARG=0.1    # sample rate 0.0–1.0 (default 1.0)

Re-exports§

pub use baggage::Baggage;

Modules§

baggage
W3C Baggage (https://www.w3.org/TR/baggage/): application key/value pairs that travel with a request across services in the baggage header.
metrics
OTLP metrics export: http.server.request.duration pushed to an OpenTelemetry collector over OTLP/HTTP (JSON), every interval, with cumulative temporality and the semantic convention’s explicit buckets.

Structs§

CapturingExporter
Captures spans in memory instead of exporting them. Use in unit tests via setup_with_exporter to prove that a span was actually recorded, not just that its getters return the right values.
Context
The current span context and baggage, captured to carry across threads: Context::attach it on another thread (or around an async block run elsewhere) and spans started there become children of the captured span. rws does this itself for AsyncAppWithState handlers.
ContextGuard
Returned by Context::attach; restores the previous context on drop. Must be dropped on the thread that attached it.
DetachedSpan
A span for async work, which may resume on another thread: it’s Send, takes its parent from the context current where it starts, and is never on the thread-local stack (so spans can’t nest under it implicitly — use DetachedSpan::enter for synchronous work that should). rws uses it for database queries and the async HTTP client.
OtelLayer
Middleware that creates an HTTP server span for each request.
OtlpHttpExporter
Send spans to an OTLP-compatible collector over HTTP (JSON encoding).
Span
A single open span. Create one with span or client_span (or Span::new for full control over SpanKind); it becomes the “current” span on this thread until it’s dropped (or Span::end is called explicitly, which is equivalent).
SpanData
A completed span ready for export.
StdoutExporter
Print one JSON line per span to stdout. Useful for development and for piping into jq or a log aggregator.
TraceContext
Parsed W3C traceparent header value.
TracingConfig
Configuration for the tracing subsystem.

Enums§

AttributeValue
A span attribute value — matches OTLP AnyValue’s basic variants.
ExporterConfig
Which backend to export spans to.
SpanKind
OTLP SpanKind. Numbering matches the OTLP spec (INTERNAL=1, SERVER=2, CLIENT=3) so the numeric value can be cast directly with as i32 when building OTLP JSON. PRODUCER/CONSUMER are intentionally not exposed — nothing in this crate does message-queue instrumentation yet.

Traits§

Exporter
Destination for completed spans.

Functions§

client_span
Start a new SpanKind::Client child span for an outbound call to another service (an HTTP request, a gRPC call, …).
current_baggage
The current request’s W3C baggage (empty outside a traced request).
current_traceparent
Return the W3C traceparent value for the innermost span currently being processed on this thread (the deepest active Span, not necessarily the request root). Returns None when no span is active.
detached_span
Start a DetachedSpan under the current span; None outside a traced request (it never starts a trace of its own).
flush
Flush buffered spans without shutting down. Useful in tests.
is_tracing
Whether a span is active on this thread (and a tracer is set up).
new_span_id
Generate a new random 64-bit span ID (never all zeros).
new_trace_id
Generate a new random 128-bit trace ID (never all zeros).
parse_headers
OTEL_EXPORTER_OTLP_HEADERS syntax: key=value pairs separated by commas, values percent-decoded.
propagation_headers
traceparent and baggage header values for an outbound request made under the current span; None outside a traced request.
set_baggage
Add key=value to the current request’s baggage, so outbound calls made from here on carry it (and spans started from here on share it). Returns false outside a traced request or for a key that isn’t a token.
setup
Initialize tracing with an explicit config. Call once at startup before the server starts accepting requests.
setup_from_env
Initialize tracing from standard OpenTelemetry environment variables:
setup_with_exporter
Like setup, but takes the exporter directly instead of building one from TracingConfig::exporter. Lets you wire in any Exporter — including CapturingExporter — through the same code path production code uses, rather than only ExporterConfig’s three built-in choices.
shutdown
Flush all buffered spans to the exporter. Call before the process exits to ensure no spans are lost.
span
Start a new SpanKind::Internal child span nested under the currently active span (or a fresh trace if none is active). Use for internal work like a database query or cache lookup.
traces_configured
Whether the environment asks for OTLP trace export: an endpoint is set and OTEL_TRACES_EXPORTER isn’t none. The rws binary traces requests only then.