Python › Debugging & Profiling
How would you use the 'logging' module's exception logging (logger.exception()) INSIDE an except block to automatically capture the full traceback?
AdvancedAnswer
logger.exception(message) is a convenience method equivalent to logger.error(message, exc_info=True) — it MUST be called from WITHIN an except block (where sys.exc_info() has current exception data), and automatically appends the full traceback to the log record, avoiding the need to manually call traceback.format_exc().
import logging
logger = logging.getLogger(__name__)
try:
result = 1 / 0
except ZeroDivisionError:
logger.exception("Failed to calculate result") # automatically includes the full tracebackReal-world example Automatically logging complete diagnostic tracebacks for unexpected errors caught in a production service's exception handlers.