Sub topic 8
Logging exceptions with tracebacks
This chapter assumes you know try/except, can create a named logger with logging.getLogger(__name__), and have used basicConfig. It shows how to record an error together with its traceback, so a log entry tells you where the failure happened and not only that it happened.
Why a message alone is not enough
A message such as "Division failed" says what went wrong but not where. The traceback records the call chain and the line that raised the error. If you catch an exception and log only a message, that information is lost.
logger.exception
logger.exception() logs at ERROR level and appends the traceback of the exception being handled.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
1 / 0
except ZeroDivisionError:
logger.exception("Division failed")The output has the message line, followed by the traceback and the final ZeroDivisionError: division by zero line.
Call it only from inside an except block. Outside one, there is no active exception, and the log shows NoneType: None where the traceback should be.
exc_info for other levels
exception() always uses ERROR. To attach a traceback at another level, pass exc_info=True to the normal methods.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def read_port(text):
try:
return int(text)
except ValueError as err:
logger.warning("Bad port %r, using 8080", text, exc_info=True)
return 8080
print(read_port("abc"))
logger.critical("Giving up", exc_info=ValueError("manual example"))exc_info accepts three kinds of value:
True, which means "use the exception currently being handled".- An exception instance, which is useful when you hold the error but are outside the
exceptblock. The traceback comes from the instance's__traceback__. An instance that was never raised has none, so the log shows only its type and message. - A tuple in the form returned by
sys.exc_info().
logger.exception("msg") is shorthand for logger.error("msg", exc_info=True).
How the traceback travels
The logger stores the exception information on the LogRecord as record.exc_info. The handler's formatter turns it into text and adds it after the formatted message. This is why a custom formatter must handle exc_info itself, as the JSON formatter chapter shows.
Replace the above with the following diagram.
Common mistakes
- Logging the error twice. If you log an exception and then re-raise it, the caller may log it again. Log at the place where you handle the error, not at every layer.
- Formatting the exception into the message.
logger.error(f"Failed: {err}")drops the traceback. Uselogger.exception("Failed")instead. - Swallowing the error silently. Logging is not handling. Decide whether to return a fallback value, re-raise, or exit.
- Using
print(traceback.format_exc()). This bypasses handlers, levels, and files.
Re-raising with context
When you wrap an error, log once and chain the exception so the original cause is kept.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def load_config(path):
try:
with open(path, encoding="utf-8") as f:
return f.read()
except OSError as err:
logger.exception("Cannot read config %s", path)
raise RuntimeError("Configuration unavailable") from err
try:
load_config("missing.toml")
except RuntimeError:
passExercise
A function catches a KeyError and calls logger.error("Lookup failed: %s", err). The log shows no traceback. Give two ways to change the call so the traceback is included.
Show answer
Replace it with logger.exception("Lookup failed") inside the except block, or keep logger.error and add exc_info=True. Both attach the traceback from the exception being handled.