#axum #tracing #opentelemetry

axum-tracing-opentelemetry

Middlewares and tools to integrate axum + tracing + opentelemetry

2 unstable releases

Uses new Rust 2021

0.3.0 Aug 4, 2022
0.2.1 Jun 11, 2022

#223 in Web programming

Download history 22/week @ 2022-06-10 36/week @ 2022-06-17 72/week @ 2022-06-24 70/week @ 2022-07-01 75/week @ 2022-07-08 47/week @ 2022-07-15 24/week @ 2022-07-22 299/week @ 2022-07-29 1308/week @ 2022-08-05

1,690 downloads per month

CC0 license

30KB
512 lines

axum-tracing-opentelemetry

crates license crate version

Project Status: Active – The project has reached a stable, usable state and is being actively developed.

Middlewares and tools to integrate axum + tracing + opentelemetry.

  • Read OpenTelemetry header from incoming request
  • Start a new trace if no trace found in the incoming request
  • Trace is attached into tracing'span

For examples, you can look at:

//...
use axum_tracing_opentelemetry::opentelemetry_tracing_layer;
use axum_tracing_opentelemetry::{
    // optional tools to init tracer (may require features)
    init_tracer,
    make_resource,
    CollectorKind,
};

fn init_tracing() {

    let otel_tracer = init_tracer(
        CollectorKind::Otlp,
        make_resource(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")),
    )
    .expect("setup of Tracer");
    let otel_layer = tracing_opentelemetry::layer().with_tracer(otel_tracer);

    let subscriber = tracing_subscriber::registry()
        //...
        .with(otel_layer);
    tracing::subscriber::set_global_default(subscriber).unwrap();
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    init_tracing();
    let app = app();
    // run it
    let addr = &"0.0.0.0:3000".parse::<SocketAddr>()?;
    tracing::warn!("listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .with_graceful_shutdown(shutdown_signal())
        .await?;
    Ok(())
}

fn app() -> Router {
    // build our application with a route
    Router::new()
        .route("/health", get(health))
        // opentelemetry_tracing_layer setup `TraceLayer`, that is provided by tower-http so you have to add that as a dependency.
        .layer(opentelemetry_tracing_layer())
}

async fn shutdown_signal() {
    //...
    opentelemetry::global::shutdown_tracer_provider();
}

To retrieve the current trace_id (eg to add it into error message (as header or attributes))

  let trace_id = axum_tracing_opentelemetry::find_current_trace_id();
  json!({ "error" :  "xxxxxx", "trace_id": trace_id})

History

0.3

  • Allow customization of exporter pipeline
  • Fix name of the root span (#6)

0.2

  • First public release as a crate

0.1

Dependencies

~9–16MB
~283K SLoC