Advertisement
Intermediate Python, Debugging & Profiling

How do you use the traceback module to capture and format a full exception traceback as a string, useful for logging?

Short answer

traceback.format_exc() returns the current exception's full traceback (including file names, line numbers, and the exception message) as a formatted string, letting you log or store detailed error diagnostics rather than just the bare exception message.

Save Python mock interview
Advertisement
AModel answer
traceback.format_exc() returns the current exception's full traceback (including file names, line numbers, and the exception message) as a formatted string, letting you log or store detailed error diagnostics rather than just the bare exception message.
import traceback

try:
    1 / 0
except ZeroDivisionError:
    error_details = traceback.format_exc()
    logging.error(f"Operation failed:\n{error_details}")
Real-world example
Logging a complete, detailed stack trace to a file or monitoring service when an unexpected exception occurs in production.
Likely follow-ups
  • What's the difference between traceback.format_exc() and traceback.print_exc()?
Related topics