Skip to content

Python log stack trace

  • by

Logging the stack trace in Python allows capturing and recording the sequence of function calls when an exception occurs. By using modules such as traceback and logging, developers can log detailed information about the execution flow, including file names, line numbers, and function names.

To log a stack trace in Python, you can use the traceback module along with a logging framework like logging. Here’s the syntax to log a stack trace:

import logging
import traceback

# Configure the logging
logging.basicConfig(filename='app.log', level=logging.ERROR)

try:
    # Your code here...
    # Something that may raise an exception
    raise ValueError("An error occurred!")
except Exception as e:
    # Log the stack trace
    logging.error("An exception occurred: %s", str(e))
    logging.error(traceback.format_exc())

This enables effective debugging and troubleshooting, as it provides insights into the exact location and context of exceptions within the codebase.

Python log stack trace example

Here’s an example that demonstrates how to log a stack trace using the traceback module and the logging framework in Python:

import logging
import traceback

# Configure the logging
logging.basicConfig(filename='app.log', level=logging.ERROR)


def divide_numbers(a, b):
    try:
        result = a / b
        return result
    except Exception as e:
        # Log the exception and stack trace
        logging.error("An exception occurred: %s", str(e))
        logging.error(traceback.format_exc())


# Example usage
result = divide_numbers(10, 0)
print(result)

We then call the divide_numbers() function with arguments 10 and 0, which will trigger a ZeroDivisionError. The exception will be caught, and the stack trace will be logged to the file specified in the logging configuration (app.log in this case).

Another code

import logging
import traceback

# Configure the logging
logging.basicConfig(filename='app.log', level=logging.ERROR)

def divide_numbers(a, b):
    try:
        result = a / b
        return result
    except Exception as e:
        # Log the exception and stack trace
        logging.error("An exception occurred: %s", str(e))
        logging.error(traceback.format_exc())
        print("An exception occurred: ", str(e))
        print("Stack trace:")
        traceback.print_exc()

# Example usage
result = divide_numbers(10, 0)
print(result)  # None

Output:

Python log stack trace

After logging the stack trace, the program continues to execute, and the None value is assigned to the result variable.

By logging the stack trace, you can gain valuable insights into the execution flow of your program and diagnose issues more effectively. It helps you identify the root cause of an exception by showing the exact location in the code where the exception was raised, as well as the series of function calls that led to that point.

Do comment if you have any doubts or suggestions on this Python log topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading