How to Log Exceptions with traceback.format_exc in Python

Capture and log a full traceback string when an exception occurs using Python's traceback.format_exc() and logging module.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 14 views 0 copies

Python code

18 lines
Python 3.9+
import traceback
import logging

def risky_operation(value):
    return 10 / value

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

def main():
    try:
        result = risky_operation(0)
        print(f"Result: {result}")
    except ZeroDivisionError:
        error_msg = traceback.format_exc()
        logging.error("Exception occurred:\n%s", error_msg)

if __name__ == "__main__":
    main()

Output

stdout
2025-04-09 14:32:15,123 - ERROR - Exception occurred:
Traceback (most recent call last):
  File "example.py", line 11, in main
    result = risky_operation(0)
  File "example.py", line 5, in risky_operation
    return 10 / value
ZeroDivisionError: division by zero

How it works

The traceback.format_exc() function returns the full traceback of the currently handled exception as a string, which is perfect for logging. The logging.basicConfig sets up a handler that writes error messages to stderr with a timestamp and level name. Inside the except block, format_exc captures the exception's traceback even though the exception was already caught. The %s placeholder in the logging call ensures the multiline traceback is formatted properly and not truncated by logging's default line handling.

Common mistakes

  • Using `traceback.print_exc()` instead of `format_exc()` which prints to stdout directly rather than returning a string for logging
  • Logging the exception object with `%s` instead of `%s` with the formatted traceback, losing stack frames
  • Forgetting to call `format_exc()` inside the `except` block where the exception is still active
  • Using `logging.exception()` which adds the traceback automatically but duplicates it if you also call `format_exc`

Variations

  1. Replace `logging.error` with `logging.exception("message")` to auto-include the current exception's traceback
  2. Use `logger.exception` inside an except block for a more concise alternative that appends traceback details

Real-world use cases

  • Logging failed API calls or database operations in a web application to diagnose issues in production.
  • Capturing stack traces in background job workers when tasks fail, so errors can be analyzed via log aggregation tools.
  • Recording full tracebacks in CLI scripts for debugging user-reported errors without exposing sensitive details in terminal output.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.