Skip to main content

How to Log an Exception with Its Traceback in Python with logger.exception

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When a program catches an error and keeps going, the error still needs to be recorded, with enough detail to find the line that failed. logger.exception() writes your message and the full traceback in one call. This guide catches a division by zero and logs it, with real output from Python 3.15.2.

Syntax​

Syntax
try:
<code that may fail>
except <ExceptionType>:
logger.exception("<what went wrong>")
PartWhat it means
loggerA logger, from logging.getLogger("<name>")
logger.exception("<what went wrong>")Logs the message at ERROR level, then the traceback of the exception being handled

Python's logging documentation: "Logs a message with level ERROR on this logger." And: "Exception info is added to the logging message. This method should only be called from an exception handler."

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

log_exception.py
import logging

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("shop")


def average(prices: list[float]) -> float:
return sum(prices) / len(prices)


try:
average([])
except ZeroDivisionError:
logger.exception("Couldn't work out the average price")

print("The program carries on.")

The log_exception.py script in a macOS-style code window: logging is set up with a level name, logger name and message format, an average function divides by the length of the list, and a call with an empty list is wrapped in try with logger.exception in the except block.

  • logging.basicConfig(...) sends log lines to the terminal, each as the level, the logger's name and the message.
  • average([]) divides by len([]), which is 0, so it raises ZeroDivisionError.
  • logger.exception(...) runs inside except, where Python knows which exception is being handled.

Step 2: Run It​

Terminal
uv run python log_exception.py
Output
ERROR shop: Couldn't work out the average price
Traceback (most recent call last):
File "/Users/you/source/python-basics/log_exception.py", line 12, in <module>
average([])
~~~~~~~^^^^
File "/Users/you/source/python-basics/log_exception.py", line 8, in average
return sum(prices) / len(prices)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
The program carries on.

The output in a terminal: an ERROR line from the shop logger saying it couldn't work out the average price, the traceback down to return sum(prices) / len(prices) on line 8, ZeroDivisionError: division by zero, then The program carries on.

The log line came first, at ERROR level, then the traceback pointing at line 8, where the division failed. Then the last line printed: logging the exception didn't stop the program.

Common Mistakes​

MistakeWhat happensDo this instead
Calling logger.exception() outside an except blockThe message is logged, followed by NoneType: None instead of a tracebackUse logger.error() when there's no exception
logger.error() inside exceptOnly the message is logged, without the tracebackUse logger.exception(), or logger.error(..., exc_info=True)
Expecting logger.exception() to stop the programIt only logs: the code after the try keeps runningAdd raise after it when the caller must still see the error

Troubleshooting​

SymptomLikely causeFix
NoneType: None under a log lineexception() ran with no exception being handledMove the call into the except block

FAQ​

Is logger.exception() the same as logger.error(..., exc_info=True)?​

Both log at ERROR level with the traceback: logger.error("...", exc_info=True) inside the same except printed the same kind of traceback.

Should log messages include the traceback in production?​

A traceback shows file paths and code. Keep it in your own logs, and show users a short message instead.

Conclusion​

Inside except ZeroDivisionError, logger.exception() logged the message at ERROR level with the full traceback, and the program went on to its last line.

Additional Resources​