Description
Am I bad for wanting to access logger._context
?
Here's my use case: exception logging with extra context from inner frames in the stack.
SLOG = structlog.get_logger()
def erroneous(log, a):
log = log.bind(a=a)
try:
1 / 0
except Exception as e:
e._structlog_context = log._context # This will include `a` and anything else that was already bound to the log
raise
I don't want to log directly in my exception handler because there's already code higher up the stack which does its own logging:
def main():
log = SLOG.bind(key="value")
try:
cool()
erroneous(log, 1)
yeah()
except Exception as e:
log.error("oh no", exc_info=True)
Then, I could write a processor that looks for _structlog_context
on logged exceptions and return that additional context.
Really, all this exception-handling stuff is kinda orthogonal to request I have, but it shows my motivation. This "extra context on exception" feature could be implemented without being able to access an existing log's context; however, it naturally leads me to want to attach my logger's context to these exceptions, since those loggers are already convenient containers for all the context I want to attach.
So, I'm already doing this in production, but I'm having to access the private _context
attribute. Is there some other way to get the context that I missed? Can we have a get_context()
method?
Activity
hynek commentedon Jun 25, 2020
I've already promised someone somewhere to keep
_context
around. Would you agree thatstructlog.get_context(SLOG)
might be the safer bet?chiragjn commentedon Jun 25, 2020
+1 for a public method to get the bound context.
For use cases like in OP, I use threadlocal wrapper as the context class to avoid all the passing around. But here is another use case:
We use
_context
to extract the context and put into request headers to pass it around to other micro-services which gets read and rebound, allowing us to correlate logs across services.hynek commentedon Jun 25, 2020
Also: should we return the actual context or a copy? 🤔
hynek commentedon Jun 29, 2020
I have added it in 33008b0, pls yell if something is missing.
radix commentedon Jun 29, 2020
Thanks @hynek, sorry I was not around to respond to your comment. This looks perfect.