Framework Middleware

Create a server span for every request in axum, tower, actix-web, and tonic — extract the incoming W3C traceparent, name the span after the route, and record status and errors, using crates verified against opentelemetry 0.33.

A request shows up in Sophonz as a server span. The middleware has three jobs: read traceparent from the request headers so the span continues the caller's trace, name the span METHOD /route, and set its status from the response. None of the crates on this page are Sophonz packages. Each one creates a tracing span per request, and the tracing-opentelemetry layer registered in Installation exports it.

Before you start

Extraction uses the global propagator, which does nothing until it is set. Make sure your setup function calls global::set_text_map_propagator(...) as shown in Installation.

The OpenTelemetry crates release breaking versions often, and middleware crates follow at their own pace. These are the versions that build together with opentelemetry 0.33 and tracing-opentelemetry 0.34:

CrateVersionWorks with opentelemetry 0.33
tower-http0.6Yes. It has no OpenTelemetry dependency; you extract the context yourself.
axum-tracing-opentelemetry0.42Yes. Needs axum 0.8 and Rust 1.91 or later.
tracing-actix-web0.7Yes, with the opentelemetry_0_33 feature.
actix-web-opentelemetry0.22No. It depends on opentelemetry 0.29, so its spans go to a different global provider.
tonic-tracing-opentelemetry0.42Yes. Needs tonic 0.14.

axum and tower

Two options. tower-http's TraceLayer works on any tower::Service and needs a few lines to extract the context. axum-tracing-opentelemetry does the extraction and the attributes for you.

axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.6", features = ["trace"] }
opentelemetry-http = "0.33"
use std::time::Duration;
 
use axum::{
    extract::{MatchedPath, Path, Request},
    http::StatusCode,
    response::Response,
    routing::get,
    Router,
};
use opentelemetry::global;
use opentelemetry_http::HeaderExtractor;
use tower_http::trace::TraceLayer;
use tracing::{field::Empty, Span};
use tracing_opentelemetry::OpenTelemetrySpanExt;
 
fn make_span(req: &Request) -> Span {
    let route = req
        .extensions()
        .get::<MatchedPath>()
        .map_or(req.uri().path(), MatchedPath::as_str);
    let span = tracing::info_span!(
        "request",
        otel.name = %format!("{} {}", req.method(), route),
        otel.kind = "server",
        otel.status_code = Empty,
        http.request.method = %req.method(),
        http.route = route,
        url.path = req.uri().path(),
        http.response.status_code = Empty,
    );
 
    // Continue the caller's trace: read traceparent and baggage from the headers.
    let parent = global::get_text_map_propagator(|p| p.extract(&HeaderExtractor(req.headers())));
    let _ = span.set_parent(parent);
    span
}
 
fn on_response<B>(res: &Response<B>, _latency: Duration, span: &Span) {
    span.record("http.response.status_code", res.status().as_u16());
    if res.status().is_server_error() {
        span.record("otel.status_code", "ERROR");
    }
}
 
#[tracing::instrument]
async fn get_user(Path(id): Path<u64>) -> Result<String, StatusCode> {
    if id == 0 {
        tracing::error!(user.id = id, "user lookup failed");
        return Err(StatusCode::INTERNAL_SERVER_ERROR);
    }
    Ok(format!("user {id}"))
}
 
#[tokio::main]
async fn main() {
    let (tracer_provider, logger_provider) = init_telemetry();
 
    let app = Router::new()
        .route("/users/{id}", get(get_user))
        .layer(
            TraceLayer::new_for_http()
                .make_span_with(make_span)
                .on_response(on_response),
        )
        // Added after the trace layer, so health checks produce no spans.
        .route("/healthz", get(|| async { "ok" }));
 
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
 
    let _ = tracer_provider.shutdown();
    let _ = logger_provider.shutdown();
}
  • otel.name, otel.kind, and otel.status_code are fields that tracing-opentelemetry turns into the span's name, kind, and status. Every other field becomes a span attribute. A field has to be declared in the macro, as Empty if needed, before record can fill it.
  • MatchedPath gives the route template (/users/{id}), which keeps one span name per route. It is present when the layer is added with Router::layer.
  • set_parent has to run before the span is first entered; after that it returns an error and the span keeps its own trace. make_span_with runs at the right moment.
  • TraceLayer also emits DEBUG events such as started processing request; they are attached to the server span as span events.

actix-web

actix-web = "4"
tracing-actix-web = { version = "0.7", features = ["opentelemetry_0_33"] }
use actix_web::{get, web, App, HttpServer, Responder};
use tracing_actix_web::TracingLogger;
 
#[get("/users/{id}")]
async fn get_user(id: web::Path<u64>) -> impl Responder {
    format!("user {id}")
}
 
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let (tracer_provider, logger_provider) = init_telemetry();
 
    HttpServer::new(|| App::new().wrap(TracingLogger::default()).service(get_user))
        .bind(("0.0.0.0", 3000))?
        .run()
        .await?;
 
    // run() returns after SIGINT or SIGTERM and the graceful stop.
    let _ = tracer_provider.shutdown();
    let _ = logger_provider.shutdown();
    Ok(())
}

The feature name selects the opentelemetry version the crate links against; with it enabled, TracingLogger extracts the incoming context through the global propagator and sets it as the parent. Without the feature the middleware still creates spans, but every request starts a new trace.

The root span is named METHOD /route and uses the older attribute names http.method, http.route, and http.status_code. Sophonz accepts both the older and the current HTTP attribute names. An error response fills exception.message, and a 5xx status sets otel.status_code to ERROR.

tonic

tonic = "0.14"
tonic-tracing-opentelemetry = "0.42"
tower = "0.5"
use tonic::transport::Server;
use tonic_tracing_opentelemetry::middleware::{filters, server};
 
Server::builder()
    .layer(server::OtelGrpcLayer::default().filter(filters::reject_healthcheck))
    .add_service(GreeterServer::new(greeter))
    .serve(addr)
    .await?;

The server layer reads the trace context from the gRPC metadata and opens a server span per call. For outgoing calls, wrap the channel with the client layer, which injects the context:

use tonic_tracing_opentelemetry::middleware::client::OtelGrpcLayer;
use tower::ServiceBuilder;
 
let channel = ServiceBuilder::new().layer(OtelGrpcLayer).service(channel);
let mut client = GreeterClient::new(channel);

Like axum-tracing-opentelemetry, these spans are created at TRACE level unless tracing_level_info is enabled.

Errors and status

With the default tracing-opentelemetry layer, three things mark a span as failed:

What you writeResult on the current span
tracing::error!("...") inside the spanStatus ERROR, and the event is attached as a span event.
#[tracing::instrument(err)] on a function returning ResultOn Err: status ERROR with the error's message, and an exception event with exception.message.
span.record("otel.status_code", "ERROR")Status ERROR. The field must be declared on the span.

To set a status with a message on a handled error, from anywhere inside the request:

use opentelemetry::trace::Status;
use tracing_opentelemetry::OpenTelemetrySpanExt;
 
if let Err(err) = sync_inventory().await {
    tracing::Span::current().set_status(Status::error(err.to_string()));
}

#[tracing::instrument] on a handler creates a child span, so Span::current() there is the handler's span, not the server span. A 5xx response still marks the server span through the middleware.

NOTE — 4xx responses

None of the middleware above marks a 4xx response as an error. That follows the OpenTelemetry convention for server spans: a client error is not a server failure.

Next steps