首页 > 解决方案 > Rust axum / hyper 请求局部变量

问题描述

有没有办法将变量绑定到Axum请求?

特别是,我正在尝试将请求 ID 添加到每个跟踪事件。我可以像这样使用tower::trace中间件来做到这一点:

#[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))

它在服务器范围内工作,但我还需要将请求 ID 传递到外部任务队列中。有什么建议么?

标签: rustrust-tokiohyper

解决方案


在rustlang 论坛的解决方案之后,我将它变成了一个小板条箱


推荐阅读