Logging exceptions
suggest changeCall 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents