I’m trying to parallelize logs with Queuehandler and Queuelistener in a fastapi application but the contextvars setted on the main thread does not propagate to “_monitor” thread of the QueueListener.
To contextualize, I set se contextVar on fastapi main file:
@app.middleware("http")
async def set_context_vars(request: Request, call_next: Callable) -> Any:
...
log_extras.set(extra_logs)
...
response = await call_next(request)
...
And use in it in a Formatter on a logger file.
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
...
formatted = {
...
}
formatted.update(log_extras.get())
return json.dumps(formatted)
Can anyone help me to understand how can I resolve this?