async_to_sync and thread local variable problem


I am using django-request-id-logging for attaching a request id to logging messages belonging to one request. But since a request also uses asgiref’s async_to_sync to call group_send from django views, the thread local variable isn’t available to this subthread.

According to the documentation, it says “Threadlocals and contextvars values are preserved across the boundary in both directions.”. Does it mean that they are shared?, If they are, then why isn’t the channels logger not able to get the thread local request id inside the function called by group_send?.

Same issue with websocket connect too, The middleware (First in the MIDDLEWARES identifier in creates a thread local variable, connect goes through the middleware first then to the sync consumer, but still not able to access thread local variables when doing logging.

The package you’re using is very outdated, it haven’t been patched 4 years. You’re right, it does not support ASGI or async as using thread locals directly or storing the IDs to an object no longer works. (Two approaches to the same problem before ASGI)
When the code lives on a different thread, the get thread ID functions will no longer return the ID stored for that request. This logic does not work anymore.

The solution is to use ContextVars.

If you don’t want to implement this yourself, Django-GUID already supports ASGI, and is actively maintained. If you’re missing a feature, please don’t hesitate creating an issue or a PR :slight_smile: