How to Use OpenTelemetry with Rust

Integrate OpenTelemetry with Rust by adding the axum-tracing-opentelemetry crate and applying its middleware to your Axum router.

Use the axum-tracing-opentelemetry crate to integrate OpenTelemetry with Rust web services. Add the dependency to your Cargo.toml and apply the middleware to your Axum router to automatically capture traces and metrics.

[dependencies]
axum = "0.7"
axum-tracing-opentelemetry = "0.10"
tracing = "0.1"
tracing-subscriber = "0.3"
tracing-opentelemetry = "0.23"
opentelemetry = "0.22"
opentelemetry-stdout = "0.3"
  1. Initialize the OpenTelemetry pipeline in your main function. opentelemetry::global::set_text_map_propagator(opentelemetry::propagation::TraceContext::new());
  2. Configure the tracing subscriber to use the OpenTelemetry layer. tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer)).init();
  3. Apply the axum_tracing_opentelemetry::OpenTelemetryMiddleware to your Axum router. let app = axum::Router::new().route("/", get(handler)).layer(axum_tracing_opentelemetry::OpenTelemetryMiddleware::new());
  4. Run your server with the configured router. axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()).serve(app.into_make_service()).await.unwrap();