I am implementing a custom Handler with Python. Naturally, I need to override emit(self, record) to do that. An example:
from logging import Handler, LogRecord class FooHandler(Handler): def emit(self, record: LogRecord): # handler logic As you can see, everytime I log something with a Logger instance, this will provide a LogRecord to emit method.
I see the current implementation of LogRecord from CPython source, you can also see it from here.
Assuming I have Logger instance called logger. Later somewhere in the code, I do these:
# either this logger.exception(Exception("foo")) # it does not have to be an instance of Exception, it's for the sake of simplicity # or this logger.error("foo", exc_info=True) # this also provides a stack trace on the console handler Since @thebjorn has commented about traceback module, I think I can work around from that. However I have three questions right now:
- How do I get the exception from
LogRecordinstance? - If I do
logger.error("message", exc_info=True), then I do not pass any exception instance. In this case, how do I get the traceback since I do not simply have any exception instance?
Thanks in advance.
Environment
- Python 3.5 and above
tracebackmodule..?SteamHandlerimplementation has given me a bit of insight but I still might need an explanation about handleError.