2

I'm trying to add a request id to each tracing event. I can do it with tower_http::trace like this:

#[derive(Clone)]
pub struct RequestSpan;

impl<B> tower_http::trace::MakeSpan<B> for RequestSpan {
    fn make_span(&mut self, request: &http::Request<B>) -> tracing::Span {
        tracing::error_span!(
            "rq",
            id = %ulid::Ulid::new().to_string(),
            method = %request.method(),
            uri = %request.uri(),
            version = ?request.version(),
        )
    }
}

...

let middleware_stack = tower::ServiceBuilder::new()
    .layer(TraceLayer::new_for_http().make_span_with(RequestSpan))

It works in the scope of the server, but I also need to pass the request id into an external task queue. Any suggestions?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
imbolc
  • 1,620
  • 1
  • 19
  • 32

2 Answers2

5

Custom data can be stored on requests via Extensions. They are accessible via .extensions() and .extensions_mut() on a http::request::Request (which works for hyper and tower-http) or via the same methods on axum::response::RequestParts (which works for axum).

Extensions are primarily used to move data between services/middleware to the route handler and vice-versa. The collection acts like a map with values keyed-off of their type, so if you want to store a Ulid you probably want to wrap it in some more descriptive type like RequestId(Ulid) just to ensure it doesn't conflict with other uses.

See also:

kmdreko
  • 42,554
  • 6
  • 57
  • 106
-1

I've made it into a little crate following a solution from rustlang forum

imbolc
  • 1,620
  • 1
  • 19
  • 32
  • This does not appear to answer the question: "Is there a way to bind a variable to Axum request?", and what answer there could be is obscured behind a link. It is nice that you were able to find the solution to your problem and were even able to contribute back to the community. But a user looking how to use "request local variables" in hyper/axum/tower will have trouble applying this answer to their use-case. – kmdreko Sep 17 '22 at 02:59