exception – How do I log a Python error with debug information?

exception – How do I log a Python error with debug information?

logger.exception will output a stack trace alongside the error message.

For example:

import logging
try:
    1/0
except ZeroDivisionError:
    logging.exception(message)

Output:

ERROR:root:message
Traceback (most recent call last):
  File <stdin>, line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

@Paulo Cheque notes, be aware that in Python 3 you must call the logging.exception method just inside the except part. If you call this method in an arbitrary place you may get a bizarre exception. The docs alert about that.

Using exc_info options may be better, to allow you to choose the error level (if you use exception, it will always be at the error level):

try:
    # do something here
except Exception as e:
    logging.critical(e, exc_info=True)  # log exception info at CRITICAL log level

exception – How do I log a Python error with debug information?

One nice thing about logging.exception that SiggyFs answer doesnt show is that you can pass in an arbitrary message, and logging will still show the full traceback with all the exception details:

import logging
try:
    1/0
except ZeroDivisionError:
    logging.exception(Deliberate divide by zero traceback)

With the default (in recent versions) logging behaviour of just printing errors to sys.stderr, it looks like this:

>>> import logging
>>> try:
...     1/0
... except ZeroDivisionError:
...     logging.exception(Deliberate divide by zero traceback)
... 
ERROR:root:Deliberate divide by zero traceback
Traceback (most recent call last):
  File <stdin>, line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

Leave a Reply

Your email address will not be published. Required fields are marked *