Expand description
OpenTelemetry-compatible distributed tracing.
OtelLayer is a Middleware that:
- Reads the W3C
traceparentheader from incoming requests and continues an existing trace, or starts a fresh one. - Creates an HTTP server span with standard semantic attributes.
- Stores the active span context in thread-local storage so downstream
middleware (e.g.
crate::proxy::ReverseProxy) can propagate it. - 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
baggageheader. - metrics
- OTLP metrics export:
http.server.request.durationpushed to an OpenTelemetry collector over OTLP/HTTP (JSON), everyinterval, with cumulative temporality and the semantic convention’s explicit buckets.
Structs§
- Capturing
Exporter - Captures spans in memory instead of exporting them. Use in unit tests via
setup_with_exporterto 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::attachit on another thread (or around anasyncblock run elsewhere) and spans started there become children of the captured span. rws does this itself forAsyncAppWithStatehandlers. - Context
Guard - Returned by
Context::attach; restores the previous context on drop. Must be dropped on the thread that attached it. - Detached
Span - A span for
asyncwork, which may resume on another thread: it’sSend, 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 — useDetachedSpan::enterfor synchronous work that should). rws uses it for database queries and the async HTTP client. - Otel
Layer - Middleware that creates an HTTP server span for each request.
- Otlp
Http Exporter - Send spans to an OTLP-compatible collector over HTTP (JSON encoding).
- Span
- A single open span. Create one with
spanorclient_span(orSpan::newfor full control overSpanKind); it becomes the “current” span on this thread until it’s dropped (orSpan::endis called explicitly, which is equivalent). - Span
Data - A completed span ready for export.
- Stdout
Exporter - Print one JSON line per span to stdout. Useful for development and for
piping into
jqor a log aggregator. - Trace
Context - Parsed W3C
traceparentheader value. - Tracing
Config - Configuration for the tracing subsystem.
Enums§
- Attribute
Value - A span attribute value — matches OTLP
AnyValue’s basic variants. - Exporter
Config - Which backend to export spans to.
- Span
Kind - OTLP
SpanKind. Numbering matches the OTLP spec (INTERNAL=1,SERVER=2,CLIENT=3) so the numeric value can be cast directly withas i32when building OTLP JSON.PRODUCER/CONSUMERare 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::Clientchild 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
traceparentvalue for the innermost span currently being processed on this thread (the deepest activeSpan, not necessarily the request root). ReturnsNonewhen no span is active. - detached_
span - Start a
DetachedSpanunder the current span;Noneoutside 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_HEADERSsyntax:key=valuepairs separated by commas, values percent-decoded.- propagation_
headers traceparentandbaggageheader values for an outbound request made under the current span;Noneoutside a traced request.- set_
baggage - Add
key=valueto the current request’s baggage, so outbound calls made from here on carry it (and spans started from here on share it). Returnsfalseoutside 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 fromTracingConfig::exporter. Lets you wire in anyExporter— includingCapturingExporter— through the same code path production code uses, rather than onlyExporterConfig’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::Internalchild 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_EXPORTERisn’tnone. Therwsbinary traces requests only then.