← Back to Python, page 3

python-0047 · Medium mid

How should logging be set up instead of print statements?

Create a logger per module with logging.getLogger(__name__), configure handlers and levels once at the application entry point, and log with lazy %-style arguments. Use levels (DEBUG to CRITICAL) to filter output and logger.exception inside except blocks to include tracebacks.

Full answer
python
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                    format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("shop.orders")

def place(order_id, qty):
    log.debug("validating %s", order_id)
    if qty <= 0:
        log.warning("rejected order %s: qty=%s", order_id, qty)
        return False
    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("failed to price order %s", order_id)
    log.info("placed order %s", order_id)
    return True

place(7, 0)
place(8, 2)
logging.getLogger("shop").setLevel(logging.ERROR)
place(9, 0)
print("done")

Output:

text
WARNING shop.orders: rejected order 7: qty=0
ERROR shop.orders: failed to price order 8
Traceback (most recent call last):
  File "<stdin>", line 12, in place
ZeroDivisionError: division by zero
INFO shop.orders: placed order 8
done

The DEBUG message is not shown because the level is INFO. log.exception logs at ERROR and appends the traceback. Setting the parent logger 'shop' to ERROR silences the warning for order 9, because child loggers inherit their effective level. Passing arguments instead of f-strings defers formatting until a handler actually emits the record. Libraries should never call basicConfig; only the application configures handlers, often with JSON formatters for log aggregation.

python
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                    format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("shop.orders")

def place(order_id, qty):
    log.debug("validating %s", order_id)
    if qty <= 0:
        log.warning("rejected order %s: qty=%s", order_id, qty)
        return False
    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("failed to price order %s", order_id)
    log.info("placed order %s", order_id)
    return True

place(7, 0)
place(8, 2)
logging.getLogger("shop").setLevel(logging.ERROR)
place(9, 0)
print("done")

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • One logger per module via __name__
  • Configure once at the entry point
  • Levels filter messages
  • logger.exception adds tracebacks
  • Lazy formatting with arguments

Common mistakes

  • Calling basicConfig in library code
  • Using print for operational logs

Follow-ups

  • How would you log JSON for a log aggregator?
  • How do logger hierarchies work?

Tips

  • Show level filtering