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

Better Stack Team
Updated on October 5, 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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github