Hacker News new | ask | show | jobs
by paulfurtado 1456 days ago
It's definitely sad that there isn't built-in context support, but if you're looking for a solution to this, it is actually very easy to attach context to logs using threadlocal and a logging filter.

When running a webserver though, an even simpler trick is to add middleware that sets the current request's info as the current thread's name, and then including threadName in your log format.

3 comments

ContextVars are seemingly more robust and work with async. We use them quite extensively for adding context to logs.
I was going to say the same, I combine ContextVars with LoggerAdapters[1].

[1] https://docs.python.org/3/library/logging.html#logging.Logge...

TIL that ContextVars can work in place of thread locals too. Thanks for pointing that out!

I had mistakenly assumed ContextVars only worked for async code.

The contextual support is lacking but it can be done. See this comment from a previous discussion where I briefly described how I’ve used the record factory to help: https://news.ycombinator.com/item?id=31484527
Take a look at pylogctx maybe it'll do what you need.