1

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.

aknuds1
  • 65,625
  • 67
  • 195
  • 317

2 Answers2

5

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)
aknuds1
  • 65,625
  • 67
  • 195
  • 317
  • For Python 2.7 you can use [`sys.exc_info()`](https://docs.python.org/2/library/sys.html#sys.exc_info) to get the traceback of the exception currently being handled. – Lukas Graf Jul 21 '14 at 12:19
  • @LukasGraf I know, but this question deals with general exception objects. – aknuds1 Jul 21 '14 at 12:23
  • You can simply use: `logger.error('Exception occurred', exc_info=exc)`. Python itself will [extract exception type/traceback info](https://github.com/python/cpython/blob/v3.7.1rc2/Lib/logging/__init__.py#L1513). – Masood Khaari Oct 15 '18 at 12:57
0

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.

theCowardlyFrench
  • 228
  • 1
  • 3
  • 11