How can I log an exception object with its traceback in Python 3, using the standard logging module?
Note that the exception in question isn't necessarily the one currently being handled.
Logger objects accept an exc_info
argument to include exception information (including traceback), which is expected to be a tuple containing the exception's class, the exception itself and the exception's traceback. The trickiest part is to get hold of the traceback, but it turns out that since Python 3.0, exceptions have a __traceback__
attribute:
logger = logging.getLogger()
exc_info = (type(exc), exc, exc.__traceback__)
logger.error('Exception occurred', exc_info=exc_info)
Honestly I don't know if I'm contributing in the slightest by doing this, but I did find this resource that I thought pertinent to your question and I hope useful.
http://www.alexconrad.org/2013/02/loggingexception.html
The gist of it being, if you place logging.exception() inside of an except block, then you can log all of your errors.