Python Standard Library · Lesson 124 of 149

Python logging

What you will learn

  • Why logging is better than print for diagnostics
  • The levels: DEBUG, INFO, WARNING, ERROR, CRITICAL
  • basicConfig, format strings
  • Named loggers and log.exception
  • Handlers and formatters: console and file
  • Good habits, including library etiquette

1. Why not just print?

print is fine for output the user wants to see. For diagnostic messages ("order 7 placed", "disk almost full", "payment failed") it falls short: you cannot turn the messages on and off without editing code, you cannot send them to a file as well as the screen, they carry no time or severity, and they mix with the program's real output.

The logging module solves this: you write log messages with a severity level, and configuration, separate from the code, decides what is shown, where, and in what format.

import logging

2. Levels

Every message has a level of importance:

Level Number Use for
DEBUG 10 detailed information for developers
INFO 20 normal events ("started", "order placed")
WARNING 30 something unexpected, but the program continues
ERROR 40 a failure of one operation
CRITICAL 50 a serious failure; the program may stop

A logger has a threshold: messages below it are ignored. The default threshold is WARNING:

logging.warning("careful")
logging.info("hidden by default")
logging.debug("hidden")
logging.error("bad")
print(logging.getLogger().level, logging.WARNING)
WARNING:root:careful
ERROR:root:bad
30 30

The message format shows LEVEL:logger name:message; "root" is the name of the default logger. INFO and DEBUG were dropped because they are below the threshold.

Quick check: with the default setup, is `logging.info("x")` printed?

No. The default threshold is WARNING (30), and INFO is 20.

3. basicConfig

logging.basicConfig(...) sets up the root logger with a level and a format. Call it once, at the start of the program (not in library code):

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
    datefmt="%H:%M:%S",
)
log = logging.getLogger("shop.orders")

log.debug("details: %s", {"id": 7})
log.info("order %d placed by %s", 7, "Rina")
log.warning("stock low")
log.error("payment failed")
log.critical("shutting down")
HH:MM:SS | DEBUG    | shop.orders | details: {'id': 7}
HH:MM:SS | INFO     | shop.orders | order 7 placed by Rina
HH:MM:SS | WARNING  | shop.orders | stock low
HH:MM:SS | ERROR    | shop.orders | payment failed
HH:MM:SS | CRITICAL | shop.orders | shutting down

(HH:MM:SS stands for the actual time, which changes on every run.) The format string uses these fields:

Field Meaning
%(asctime)s the time
%(levelname)s INFO, ERROR... (%-8s pads to 8 characters)
%(name)s the logger's name
%(message)s your message
%(funcName)s, %(lineno)d, %(filename)s where the call was made

Logger names and %s arguments

logging.getLogger("shop.orders") returns the logger with that name. The usual convention is one logger per module, named after it:

log = logging.getLogger(__name__)

Names with dots form a hierarchy: shop.orders is a child of shop, which is a child of the root. Settings flow down the tree (section 6).

Notice the way arguments are passed: log.info("order %d placed by %s", 7, "Rina"). The values are given separately, and the string is only built if the message is actually going to be shown. Compare with an f-string, which is formatted every time, even for hidden DEBUG messages. Both produce the same text (log.info(f"fstring {x}") printed fstring 5), but the %s style is the convention for logging, and it also lets tools group similar messages.

4. Logging exceptions

Inside an except block, log.exception(message) logs at the ERROR level and appends the full traceback (lesson 14.2):

try:
    1 / 0
except ZeroDivisionError:
    log.exception("calculation failed")
HH:MM:SS | ERROR    | shop.orders | calculation failed
Traceback (most recent call last):
  File "k179b.py", line 5, in <module>
    try: 1/0
         ~^~
ZeroDivisionError: division by zero

(File paths shortened.) This is far more useful than print(e): you get the time, the level and the whole story. Equivalent: log.error("...", exc_info=True). Log the exception once, at the place that handles it; do not log it and then re-raise at every layer, or the same error appears many times.

5. Handlers: where messages go

A handler sends log records to a destination, and each has its own level and formatter:

Handler Destination
StreamHandler(stream) a stream such as the screen (sys.stderr by default)
FileHandler(path) a file
RotatingFileHandler(path, maxBytes, backupCount) a file that starts a new one when it gets big
TimedRotatingFileHandler new file per day, hour...
NullHandler() nowhere (for libraries)

A typical setup: brief messages on screen, full detail in a file:

import sys

app = logging.getLogger("app")
app.setLevel(logging.DEBUG)
app.propagate = False

console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))

file = logging.FileHandler("app.log", encoding="utf-8")
file.setLevel(logging.DEBUG)
file.setFormatter(logging.Formatter("%(levelname)s|%(name)s|%(funcName)s|%(message)s"))

app.addHandler(console)
app.addHandler(file)

def work():
    app.debug("inner detail")
    app.info("started")
    app.warning("slow")

work()

Screen:

INFO: started
WARNING: slow

The file app.log:

DEBUG|app|work|inner detail
INFO|app|work|started
WARNING|app|work|slow

The logger lets everything through (DEBUG), and each handler filters further: the console shows INFO and above, the file keeps everything. Adding the same handler object twice to a logger does not duplicate output (Python ignores it), but creating a new handler every time a function is called does, a classic bug when setup code runs repeatedly.

For other formats, subclass Formatter, for example to produce JSON lines that other tools can read:

import json

class JsonFmt(logging.Formatter):
    def format(self, record):
        return json.dumps({"level": record.levelname, "msg": record.getMessage()})

With that formatter, j.info("hello %s", "x") printed {"level": "INFO", "msg": "hello x"}.

6. Propagation and the logger tree

A message sent to a child logger (app.db) travels up to its parents' handlers too, unless propagate is set to False. That is why configuring one set of handlers on the root (or top-level) logger is enough for the whole program:

child = logging.getLogger("app.db")
child.info("child message")
print(len(app.handlers), child.level, child.getEffectiveLevel())
INFO: child message
2 0 10
  • child.level is 0 ("not set"), so it uses its parent's level: getEffectiveLevel() is 10 (DEBUG).
  • The console handler of app showed the child's message, and the file would have received it too.

Therefore: libraries and modules just call logging.getLogger(__name__) and log; the application configures handlers once, near its start.

Library etiquette

If you write a library that others import, do not call basicConfig or add real handlers: that is the application's business. Add a NullHandler to your top-level logger, so that nothing is printed unless the application configures logging:

logging.getLogger("mylib").addHandler(logging.NullHandler())

7. What to log, and what not

Do Do not
log events that help you understand what happened: starts, stops, decisions, failures log inside tight loops at INFO
include identifiers (order id, user id) log passwords, tokens, card numbers or personal data
use the right level use ERROR for ordinary conditions
log exceptions with log.exception swallow errors silently
configure once, in the main program call basicConfig in modules

For bigger projects, logging.config.dictConfig loads the whole setup from a dictionary (for example from a JSON or YAML settings file).

Worked example: processing orders with two outputs

setup_logging sends WARNING and above to the screen (or everything with verbose=True) and everything to orders.log. The functions only log; they know nothing about where messages go.

import logging
import sys

log = logging.getLogger("orders")


def setup_logging(verbose=False, logfile="orders.log"):
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    console = logging.StreamHandler(sys.stdout)
    console.setLevel(logging.DEBUG if verbose else logging.WARNING)
    console.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
    file = logging.FileHandler(logfile, encoding="utf-8")
    file.setFormatter(logging.Formatter("%(levelname)-7s %(name)s.%(funcName)s: %(message)s"))
    root.handlers[:] = [console, file]


def total(order):
    log.debug("pricing order %s", order["id"])
    if not order["items"]:
        log.warning("order %s has no items", order["id"])
        return 0
    return sum(price * qty for price, qty in order["items"])


def process(orders):
    done = 0
    for order in orders:
        try:
            amount = total(order)
            log.info("order %s total %s", order["id"], amount)
            done += 1
        except (KeyError, TypeError):
            log.exception("order %s is malformed", order.get("id", "?"))
    log.info("%d of %d orders processed", done, len(orders))
    return done


setup_logging(verbose=False)
orders = [{"id": 1, "items": [(2.5, 2), (1.0, 3)]},
          {"id": 2, "items": []},
          {"id": 3}]
print("processed:", process(orders))
print("--- file contents:")
print(open("orders.log", encoding="utf-8").read(), end="")

Output (the traceback's file paths are shortened):

WARNING: order 2 has no items
ERROR: order 3 is malformed
Traceback (most recent call last):
  File "w179.py", line 30, in process
    amount = total(order)
  File "w179.py", line 20, in total
    if not order["items"]:
           ~~~~~^^^^^^^^^
KeyError: 'items'
processed: 2
--- file contents:
DEBUG   orders.total: pricing order 1
INFO    orders.process: order 1 total 8.0
DEBUG   orders.total: pricing order 2
WARNING orders.total: order 2 has no items
INFO    orders.process: order 2 total 0
DEBUG   orders.total: pricing order 3
ERROR   orders.process: order 3 is malformed
Traceback (most recent call last):
  File "w179.py", line 30, in process
    amount = total(order)
  File "w179.py", line 20, in total
    if not order["items"]:
           ~~~~~^^^^^^^^^
KeyError: 'items'
INFO    orders.process: 2 of 3 orders processed
Observation Why
the screen shows only the warning and the error the console handler's level is WARNING
the file has everything, including DEBUG lines the file handler has no level of its own, so it takes all records from the root logger (set to DEBUG)
%(funcName)s in the file tells you which function logged each line
order 3 did not stop the run the error was logged with its traceback, and the loop carried on
the functions know nothing about handlers change setup_logging and the destinations change

The orders are made up. Run it with verbose=True and the screen shows the DEBUG and INFO lines too.

Common mistakes

  • Using print for diagnostics in programs that run unattended.
  • Calling basicConfig in modules, or more than once (later calls are ignored when handlers already exist).
  • Building messages with f-strings in hot paths (use %s arguments).
  • Adding handlers repeatedly, producing duplicate lines.
  • Logging secrets or personal data.
  • Logging the same exception at every layer.
  • Wrong levels: everything at INFO, or normal events at ERROR.
  • Forgetting that the logger level filters before the handler level.

Key takeaways

  • Use logging instead of print for diagnostics: levels DEBUG, INFO, WARNING, ERROR, CRITICAL (default threshold WARNING).
  • Get a logger per module with logging.getLogger(__name__); pass values as arguments (log.info("order %s", id)).
  • log.exception records an error with its traceback.
  • Handlers decide destinations and levels; formatters decide layout; configure them once in the application (basicConfig or handlers).
  • Child loggers propagate to their parents; libraries add only a NullHandler.
  • Never log secrets.

Practice

1. Which levels are shown by default?

Show answer

WARNING, ERROR and CRITICAL.

2. Why write log.info("user %s logged in", name) rather than log.info(f"user {name} logged in")?

Show answer

The text is only built if the message is actually emitted, and similar messages can be grouped by tools. It is the logging convention.

3. What does log.exception("failed") add compared with log.error("failed")?

Show answer

The full traceback of the exception being handled (it should be called inside an except block).

4. How can the screen show only warnings while the file keeps everything?

Show answer

Give the logger level DEBUG, set the console handler's level to WARNING, and leave the file handler at DEBUG.

5. What does logging.getLogger(__name__) give in module shop/orders.py?

Show answer

A logger named shop.orders, a child of shop in the logger tree.

6. Why should a library not call basicConfig?

Show answer

Logging configuration belongs to the application using the library; a library should only log, adding a NullHandler so nothing is shown unless the application configures it.