How to log a Python error with debug information (stack trace)

Better Stack Team
Updated on August 25, 2023

To log a Python error with debug information, including the stack trace, you can use the logging module. The logging module provides a flexible way to record messages from your Python code, including errors, warnings, and debug information. Here's a step-by-step guide on how to achieve this:

  1. Import the logging module:

    import logging
  2. Configure the logging settings (optional): Before logging any messages, you can configure the logging settings. This step is optional, but it allows you to customize how the logs are handled, such as specifying the log level, setting the output format, or sending logs to a specific file. For example:

    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

    This configuration sets the log level to DEBUG, which will capture all log messages of severity DEBUG and above. The log format includes the timestamp, log level, and log message.

  3. Log the error with the stack trace:

    When you encounter an error in your code, you can log it along with its stack trace using the logging.exception() method. This method logs the error message along with the traceback. Here's an example:

        # Your code that may raise an error
        result = 10 / 0  # This will raise a ZeroDivisionError
    except Exception as e:
        logging.exception("An error occurred:")

    In this example, any exception raised within the try block will be caught, and the error message along with the stack trace will be logged.

  4. Save logs to a file (optional):

    If you want to save the logs to a file instead of printing them to the console, you can add a file handler to the logger. Here's how you can do it:

    # Configure logging to a file
    logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
    # Continue with the same try-except block to log errors

    This will create a file called "app.log" in the same directory as your script and store the log messages in it.

    With these steps, you can log Python errors with debug information and have a better understanding of what went wrong in your code, including the stack trace leading up to the error.

    To learn more about logging in Python, visit Better Stack Community.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →