Skip to content

Rust async/await thread locals do not work. Is there a fix ? #4

@mateiandrei94

Description

@mateiandrei94

I'm not sure if this is a log-mdc problem or a generic problem with the entire logging system in async rust (including the log crate and all the implementations which i don't think they have async functions).
I'll post this here for now, maybe there's a solution which I can't think of (which this crate alone can solve).
The problem boils down to: Thread local variables (i.e.: MDC in logging frameworks) do not work as expected in an async fn. After an .await inside of an async fn the "runtime" (e.g.: tokio) can resume the async fn using a different thread. This is good concurrency and is what is expected from frameworks like tokio, however by switching threads we loose the "old" thread's thread local context which probably not what we want an (i think) is not what MDC is supposed to do.

===

I don't know which log implementations use this crate. I have skimmed trough log4rs source and saw this crate being used as an optional dependency.
In order to add MDC support for async/await programming i think this crate should add a "second" hash map
and related functions but instead of using regular functions they should be declared as async and instead of using thread_local! they should use tokio::task_local! (this created a dependency on tokio) but i suppose there should be a "runtime independent trait" to do that ? I'm new to rust so I don't know how deep the rabbit hole goes.

tokio::task_local

===

I posted a question on stack overflow about thread locals is async rust detailing as an example this particular situation.

https://stackoverflow.com/q/76947326/13169040

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions