Sub topic 8
Logging exceptions with tracebacks
This chapter assumes you can use try/except, you know the log levels, and you know how a logger passes records to handlers. It covers how to log an exception without losing its traceback, the options that control this, and the mistakes that make logs noisy or misleading.
Why `str(exc)` is not enough
A traceback shows where an error happened and which calls led to it. If you log only the exception message, you lose that information:
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)
def parse_port(value):
return int(value)
try:
parse_port("eighty")
except ValueError as exc:
logger.error("Lost traceback: %s", exc)
logger.exception("Keeps traceback")The first call prints one line. The second call prints the message followed by the traceback:
ERROR __main__: Lost traceback: invalid literal for int() with base 10: 'eighty'
ERROR __main__: Keeps traceback
Traceback (most recent call last):
File "demo.py", line 11, in <module>
parse_port("eighty")
File "demo.py", line 8, in parse_port
return int(value)
ValueError: invalid literal for int() with base 10: 'eighty'Python 3.11 and later add ^^^^ markers under the failing expression. The rest is the same.
logger.exception
logger.exception(msg, *args) does the same as logger.error(msg, *args, exc_info=True). It logs at ERROR and attaches the exception currently being handled. Call it from inside an except block, where that exception exists.
The message should say what the program was trying to do, such as "Could not load config for tenant 7". The traceback already shows the exception type and text, so don't repeat them in the message.
Use lazy %s arguments as with any log call. The logger builds the string only if a handler will emit the record.
The exc_info argument
Every logging method (debug, info, warning, error, critical, log) accepts exc_info. This lets you attach a traceback at a level other than ERROR:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("myapp.cache")
def load(key):
raise KeyError(key)
try:
load("user:42")
except KeyError as exc:
logger.warning("Cache miss, using database", exc_info=True)
logger.info("Cache miss details", exc_info=exc)exc_info accepts three kinds of value:
| Value | Meaning |
|---|---|
| `True` | Call `sys.exc_info()` and use the exception being handled right now. |
| An exception instance | Use that exception and its `__traceback__`. This works on Python 3.5 and later. |
| A 3-tuple `(type, value, traceback)` | Use exactly these values. This is the shape `sys.exc_info()` returns. |
Passing an instance is useful when you catch an exception in one place and log it elsewhere, for example after collecting errors from several tasks.
A traceback at WARNING or INFO is often right for expected failures that are still worth investigating, such as a cache miss or a retryable network error. Reserve ERROR and above for failures that someone should look at.
Calling it outside an except block
If no exception is being handled, exc_info=True has nothing to attach. Python 3 does not raise an error. The record gets the placeholder text NoneType: None where the traceback should be:
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("myapp").error("Something failed", exc_info=True)If you see NoneType: None in your logs, a call to logger.exception or exc_info=True is running outside an except block. A common cause is a helper function called after the handler has finished.
What the formatter does with exc_info
The logger stores the exception on the record as record.exc_info. It does not convert it to text at that point. The text is produced later, when a handler's formatter runs.
The diagram shows where each step happens.
Formatter.format calls formatException and appends the result after the formatted message, separated by a newline. It also stores the text in record.exc_text. If another handler later formats the same record, the cached exc_text is reused and formatException is not called again.
This caching has one consequence. If you attach a custom formatter to one handler and a standard formatter to another, whichever runs first decides how the traceback looks for both. A custom formatException works reliably only when every handler on the record uses it.
Overriding formatException is the supported way to change the traceback layout. This formatter puts the whole traceback on one line, which some log shippers handle more easily:
import logging
class OneLineFormatter(logging.Formatter):
def formatException(self, exc_info):
text = super().formatException(exc_info)
return text.replace("\n", " | ")
handler = logging.StreamHandler()
handler.setFormatter(OneLineFormatter("%(levelname)s %(message)s"))
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
try:
{}["missing"]
except KeyError:
logger.exception("Lookup failed")A JSON formatter does the same thing, but puts the text in an exception field instead of appending it. The structured logging chapter builds on this.
Chained exceptions
When you write raise NewError(...) from exc, or raise inside an except block, Python links the two exceptions. The traceback printed by the logging module includes both, with a line between them:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("myapp.config")
def read_setting(raw):
try:
return int(raw)
except ValueError as exc:
raise RuntimeError("Invalid setting") from exc
try:
read_setting("abc")
except RuntimeError:
logger.exception("Startup failed")The output shows the ValueError first, then the text "The above exception was the direct cause of the following exception:", then the RuntimeError. Log only the outer exception and you still get the whole chain.
Stack information without an exception
stack_info=True appends the current call stack, which is the chain of calls leading to the log line. It does not need an exception. Use it to find out which code path reached a suspicious state:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("myapp")
def check(value):
if value < 0:
logger.warning("Negative value: %d", value, stack_info=True)
def run():
check(-1)
run()The output ends with "Stack (most recent call last):" followed by the frames. You can combine stack_info with exc_info. They answer different questions: where the code was called from, and where the failure happened.
Logging uncaught exceptions
An exception that nothing catches reaches sys.excepthook, which prints a traceback to stderr and bypasses logging. In a service whose output goes to a file or log collector, that crash would be missing from your logs. Install a hook that sends it through a logger:
import logging
import sys
import threading
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("myapp")
def log_uncaught(exc_type, exc_value, exc_tb):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_tb)
return
logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
def log_thread_exception(args):
name = args.thread.name if args.thread else "unknown"
logger.critical(
"Uncaught exception in thread %s",
name,
exc_info=(args.exc_type, args.exc_value, args.exc_traceback),
)
sys.excepthook = log_uncaught
threading.excepthook = log_thread_exception
raise RuntimeError("boom")Three details matter here:
- The hook receives the exception as separate values, so you pass them as an
exc_infotuple. There is no activeexceptblock, soexc_info=Truewould not work. KeyboardInterruptgoes to the default hook, so Ctrl+C still exits quietly.threading.excepthook(Python 3.8 and later) covers exceptions that end a thread.sys.excepthookdoes not see those.
Common mistakes
- Logging and re-raising at every level. If each layer catches, logs, and re-raises, one failure produces several tracebacks. Log an exception once, at the place that handles it for good. Intermediate layers should let it propagate, or wrap it with
raise ... from. - Swallowing the exception after logging.
logger.exception(...)followed by nothing lets the program continue as if the operation worked. Decide whether to return a fallback, retry, or re-raise. - Using
exceptionfor non-errors. It always logs atERROR. For an expected condition, uselogger.warning(..., exc_info=True)orlogger.info(...)without a traceback. - Formatting the message yourself.
logger.error(f"Failed: {exc}")builds the string even when the record is dropped. It also loses the traceback unless you addexc_info. Uselogger.exception("Failed to load %s", path). - Putting sensitive data in the exception text. Tracebacks include exception messages and sometimes values from them. Make sure tokens and passwords are not in exception messages that you log.
Exercise
A function catches OSError, calls logger.error("Write failed: %s", exc), and re-raises it with a bare raise. The caller also catches OSError and calls logger.exception("Job failed"). What is wrong with this logging, and how would you fix it?
Show answer
The first call records no traceback, because exc_info is not set. The same failure is also logged twice, once in each layer. Fix it by removing the log call from the inner function, so the exception propagates, and keeping logger.exception("Job failed") in the caller. If the inner function has useful context such as the file path, include it in the caller's message or wrap the error with raise RuntimeError("Write failed for %s" % path) from exc.
Exercise
In a script, a ValueError is raised on a worker thread and nothing catches it. Your log file has no entry for it. Which hook do you set, and why is exc_info=True not enough inside it?
Show answer
Set threading.excepthook. It runs when an exception ends a thread, which sys.excepthook does not see. Inside the hook there is no active except block, so exc_info=True would find no exception. Pass the values from the hook's argument instead: exc_info=(args.exc_type, args.exc_value, args.exc_traceback).