Is there any way to access 'request-local' state from a macro, e.g. with tokio::task_local! #2352
Replies: 3 comments 5 replies
-
The clean way to do things (and likely the fastest) would be to pass around your If that's really a problem to you, you can use a Normally, you'd have to call tokio::task_local! {
static REQUEST_ID: RequestId;
}
#[get("/")]
async fn index(rid: RequestId) {
REQUEST_ID.scope(rid, async move {
// ...
})
}
#[get("/mypage")]
async fn my_page(rid: RequestId) {
REQUEST_ID.scope(rid, async move {
// ...
})
} If that becomes to ugly or hard to maintain, you could also make your own |
Beta Was this translation helpful? Give feedback.
-
The implication that figuring out how to implement 'context' for this is not "how Rust works" (or should work) is strange to me. A fixed-length request ID is a perfectly safe data structure to store in scoped memory, and the developer experience benefits of automatically getting the request ID logged seem to me to more than justify the effort (if it's doable). Yes, as you observe, implementing this for each request handler is not ideal, though it's still perhaps better than piping an argument through every helper function. I'll look into the macro suggestion, which is again better but not ideal. I confess I'm tempted to fork the project to get around this...
...but I recognize that's probably not worth the maintenance headache I'm inviting down the line. Applying logic to or running wrapper code around all requests in a given |
Beta Was this translation helpful? Give feedback.
-
I looked briefly at using https://github.com/kmdreko/task-local but it has been abandoned in favour of tokio's tokio::task::LocalKey. (which I couldn't see how to make work) Might this approach work? |
Beta Was this translation helpful? Give feedback.
-
I am trying to write a macro to replace
println!
for logging in my Rocket application. This macro would ideally prepend a request id no matter where it was called from. I know I can pass a RequestId guard into any route handler, but I don't want to have to pipe it around through every function that logs... Any advice on how to do this?So far I have something like this:
...but obviously with a server handling concurrent requests, this will only ever log the most recently initialized request ID.
There seems to be something promising about using
tokio::task_local!
—but I can't figure out where to scope the "task-local storage value" around Rocket's request handler. E.g.Seems like this may relate to #2160
Beta Was this translation helpful? Give feedback.
All reactions