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.
Python code
18 linesimport 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
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
- Replace `logging.error` with `logging.exception("message")` to auto-include the current exception's traceback
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.