Advertisement
Advanced Python, Logging

How does logger.exception() differ from logger.error(), and when should you use it?

Short answer

logger.exception(msg) is equivalent to logger.error(msg, exc_info=True) -- it automatically attaches the current exception's traceback to the log record.

Save Python mock interview
Advertisement
AModel answer
logger.exception(msg) is equivalent to logger.error(msg, exc_info=True) -- it automatically attaches the current exception's traceback to the log record. It should only be called from within an except block; calling it outside one logs 'NoneType: None' for the traceback since there's no active exception.
try:
    1 / 0
except ZeroDivisionError:
    logging.exception('Division failed')
    # Logs the error message AND the full traceback automatically
Real-world example
A background job's except block calls logger.exception() so the full stack trace lands in the log file for later debugging, without manually calling traceback.format_exc().
Likely follow-ups
  • What does exc_info=True actually capture?
  • How do you log a traceback without re-raising the exception?
Related topics