axum-otel

Crates.ioaxum-otel
lib.rsaxum-otel
version0.29.5
created_at2025-06-02 16:57:15.121809+00
updated_at2025-09-01 10:34:36.147258+00
descriptionOpenTelemetry tracing for axum.
homepage
repositoryhttps://github.com/iamnivekx/axum-otel
max_upload_size
id1698139
size74,177
Nivek Huang (iamnivekx)

documentation

https://docs.rs/axum-otel/

README

axum-otel

A structured logging middleware for Axum web framework that integrates with OpenTelemetry.

Features

  • Structured logging middleware for Axum
  • OpenTelemetry integration
  • Request tracing
  • Metrics collection
  • Customizable span attributes

Installation

Add this to your Cargo.toml:

[dependencies]
axum-otel = "0.29.0"
axum = { version = "0.8", features = ["macros"] }
tower-http = { version = "0.6.5", features = ["trace"] }
opentelemetry = { version = "0.29.0", features = ["metrics"] }
opentelemetry_sdk = { version = "0.29.0", features = ["rt-tokio"] }
opentelemetry-otlp = { version = "0.29.0", features = ["metrics", "grpc-tonic"] }

Quick Start

use axum::{
    routing::get,
    Router,
};
use axum_otel::{AxumOtelOnFailure, AxumOtelOnResponse, AxumOtelSpanCreator};
use opentelemetry::sdk::trace::Config;
use opentelemetry_otlp::WithExportConfig;
use std::net::SocketAddr;
use tower_http::trace::TraceLayer;

fn handler() -> &'static str {
    "Hello, world!"
}

#[tokio::main]
async fn main() {
    // Initialize OpenTelemetry
    let tracer = opentelemetry_otlp::new_pipeline()
        .tracing()
        .with_exporter(
            opentelemetry_otlp::new_exporter()
                .tonic()
                .with_endpoint("http://localhost:4317")
                .with_protocol(Protocol::Grpc)
        )
        .with_trace_config(Config::default())
        .install_batch(opentelemetry::runtime::Tokio)
        .expect("Failed to initialize OpenTelemetry");

    // Build our application with a route
    let app = Router::new()
        .route("/", get(handler))
        .layer(
            TraceLayer::new_for_http()
                .make_span_with(AxumOtelSpanCreator::new().level(Level::INFO))
                .on_response(AxumOtelOnResponse::new().level(Level::INFO))
                .on_failure(AxumOtelOnFailure::new()),
        );

    // Run it
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::debug!("listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn handler() -> &'static str {
    "Hello, World!"
}

Examples

Check out the examples directory for more usage examples:

Documentation

For more detailed documentation, visit docs.rs.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under either of

at your option.

Commit count: 82

cargo fmt