License Crates.io Docs.rs

hyper-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. For special use-cases (e.g. lazily generating trace ids only in case of http errors) you can implement MakeTraceId on your own types.

```rust use std::convert::Infallible; use hyper::{Body, Request, Response}; use tower::ServiceBuilder; use hypertraceid::{SetTraceIdLayer, TraceId};

let traceidheader = "x-trace-id"; let svc = ServiceBuilder::new() .layer(SetTraceIdLayer::::new().withheadername(traceidheader)) .servicefn(|req: Request| async { let res: Result, Infallible> = Ok(Response::new(Body::empty())); res }); ```

Use with [axum]

For axum users, crate optionally provides an extractor (via the axum feature) to access the trace id in a handler.

```rust use axum::{routing::get, Router}; use axumtraceid::{SetTraceIdLayer, TraceId};

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

Use with [tracing]

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

```rust use axum::{http::Request, routing::get, Router}; use axumtraceid::{SetTraceIdLayer, TraceId}; use towerhttp::trace::TraceLayer; use tracing::infospan;

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

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

```

License

This project is licensed under the MIT license.