Logging exceptions

suggest change

Call logger.exception() from inside an exception handler to log a message and the active traceback. Catch a specific exception whenever recovery is possible:

import logging

logger = logging.getLogger(__name__)

try:
    raise ValueError("Invalid temperature: 100 °C")
except ValueError:
    logger.exception("Could not process the measurement")

Do not interpolate the exception merely to obtain its text. The traceback already contains the exception type and message. If useful context is available, pass it as structured formatting arguments:

try:
    process(record)
except ProcessingError:
    logger.exception("Could not process record %r", record.id)

To include the active traceback at another log level, pass exc_info=True:

try:
    process(record)
except ProcessingError:
    logger.warning("Skipping record %r", record.id, exc_info=True)

Python 3 exception messages are Unicode strings, so the Python 2 distinction between byte-string and Unicode exception messages no longer applies.

process, record, record.id, and ProcessingError are not defined on this page. Those two snippets show the logging call, and as written they raise NameError before it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents