1 unstable release

0.1.0 Jul 26, 2023

#1513 in HTTP server

Download history 35/week @ 2024-07-22 8/week @ 2024-07-29 14/week @ 2024-08-05 33/week @ 2024-08-12 13/week @ 2024-09-09 10/week @ 2024-09-16 43/week @ 2024-09-23 13/week @ 2024-09-30 1/week @ 2024-10-07 12/week @ 2024-10-14 12/week @ 2024-10-21 19/week @ 2024-10-28 58/week @ 2024-11-04

101 downloads per month

MIT license

14KB
282 lines

axum-trace-id

Axum middleware for adding trace ids to requests.

Basic Usage

Adding the SetTraceIdLayer<T> layer will make TraceId<T> available via the request and response extensions. The crate also provides an extractor to access the trace id in a handler. For special use-cases (e.g. lazily generating trace ids only in case of http errors) you can implement MakeTraceId on your type.

use axum::{routing::get, Router};
use axum_trace_id::{SetTraceIdLayer, TraceId};

let app: Router = Router::new()
     .route(
         "/",
         get(|trace_id: TraceId<String>| async move { trace_id.to_string() }),
     )
     .layer(SetTraceIdLayer::<String>::new());

Use with tracing

To use with tracing, you can access the requests tracing id via the extensions.

use axum::{http::Request, routing::get, Router};
use axum_trace_id::{SetTraceIdLayer, TraceId};
use tower_http::trace::TraceLayer;
use tracing::info_span;

let app = Router::new()
    .route("/", get(|| async { "" }))
    .layer(TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
        let trace_id = request.extensions().get::<TraceId<String>>().unwrap();

        info_span!("http_request", trace_id = trace_id)
    }));

License

This project is licensed under the MIT license.

Dependencies

~6–13MB
~153K SLoC