brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's log.exception writes the error message and traceback in one call

Python
~/tips/tip-python-logging-exception

log = logging.getLogger(__name__)

Log a caught exception with its full traceback at error level.

When code that uses logging catches an exception, log.error(str(e)) is a common sight. That loses the traceback. log.exception keeps it.

import logging

log = logging.getLogger(__name__)

def sync(host):
    try:
        upload(host)
    except OSError:
        log.exception("sync failed for %s", host)

It logs at ERROR level, like log.error, and then adds the traceback of the exception that’s being handled. In a log file or the journal you get your own message on the first line and the stack below it, so later you can see where it went wrong without reproducing anything.

I pass the host as an argument instead of building an f-string. Logging only formats the message when it’s actually written, and handlers that group similar errors see the same template every time.

Only call it from inside an except block. Outside one there’s no current exception, and you get your message followed by NoneType: None, which looks like a bug of its own. If you want a traceback at a different level, for example a warning for an error you expect now and then, use log.warning("...", exc_info=True) instead.

Further reading: Logger.exception

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link