4 ms·
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
by paulfurtado 4y 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.
- andrewingram 4y agoContextVars are seemingly more robust and work with async. We use them quite extensively for adding context to logs.
- nerdwaller 4y agoI was going to say the same, I combine ContextVars with LoggerAdapters[1]. [1] https://docs.python.org/3/library/logging.html#logging.LoggerAdapter https://docs.python.org/3/library/logging.html#logging.Logge...
- MapleWalnut 4y agoTIL 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.
- memco 4y agoThe 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 https://news.ycombinator.com/item?id=31484527
- 1337shadow 4y agoTake a look at pylogctx maybe it'll do what you need.