Why does calling tracing::info_span! inside a middleware causes middleware::from_fn to fail

Hi folks,

I am trying to write a middleware for my axum http server which logs the requests and responses along with adding request_id to a span. Though when I try creating the span in the middleware, the from_fn starts throwing the following error:

the trait bound `axum::middleware::FromFn<fn(axum::http::Request<axum::body::Body>, axum::middleware::Next) -> impl std::future::Future<Output = axum::http::Response<axum::body::Body>> {my_middleware}, (), axum::routing::Route, _>: tower_service::Service<axum::http::Request<axum::body::Body>>` is not satisfied

This is the body of my_middleware:

async fn my_middleware(request: Request, next: Next) -> Response {
    // do something with `request`...
    let request_id = "some-id";
    let _span = tracing::info_span!("request", %request_id).entered();

    let response = next.run(request).await;

    // do something with `response`...


If the span is removed from the middleware then the error goes away. Can someone please help me understand this behaviour?

I don't know about axum but you shouldn't hold a guard from a tracing span across an await point. See the documentation. You need to instrument the run future instead.