How to Capture and Log Tracebacks (Stack trace) in Python

Once you’ve caught an exception, you can capture and log a message with the exception info (including full stack traceback), using logging.exception() or logging.error().

With logging.exception():

# log_error.py
import logging

try:
    unknown_method()
except Exception as e:
    logging.exception("Error occurred")

With logging.error() we must set the exc_info keyword argument to True (default is False):

...

try:
    unknown_method()
except Exception as e:
    logging.error("Error occurred", exc_info=True)

In both cases, the Error occurred message is logged with level ERROR on the root logger along with the exception information.

$ python log_error.py
ERROR:root:Error occurred
Traceback (most recent call last):
  File "tb.py", line 5, in <module>
    unknown_method()
NameError: name 'unknown_method' is not defined

A bit of information on exc_info from the docs:

If exc_info does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) or an exception instance is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.

Bonus: Instead of logging directly, if you want to get/return the traceback (as string or list) in a variable for further use, then read this article.

Leave a Reply

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