Python › Debugging & Profiling

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

Intermediate

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.

Common follow-ups: What's the difference between traceback.format_exc() and traceback.print_exc()?