Python › Logging
How does logger.exception() differ from logger.error(), and when should you use it?
AdvancedAnswer
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 automaticallyReal-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().