Code

Logs Worth Reading

print() is fine for quick checks. Real programs use logging, which gives you levels, timestamps, and output you can switch on and off without touching the code.

Two rules of thumb:

  • Libraries only create loggers: log = logging.getLogger(__name__). Names form a tree (guild is the parent of guild.ferry).
  • Applications configure logging once, at startup:
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)

Levels from quiet to loud: DEBUG < INFO < WARNING < ERROR < CRITICAL. A logger set to INFO drops DEBUG messages.

Under the hood, a logger sends records to handlers (where the output goes) that use formatters (what it looks like). Bigger apps describe all of this in one dict with logging.config.dictConfig.

Pip tip: Write log.info("loaded %d tasks", n) rather than an f-string. The message is only built if it will actually be shown. Inside except, log.exception("...") also records the traceback.

Assignment

Write make_logger(name, stream, level="INFO") that:

  1. gets the logger name and sets its level
  2. removes any handlers it already has (so calling it twice doesn't double every line)
  3. adds a StreamHandler(stream) with the format "%(levelname)s %(name)s: %(message)s"
  4. sets propagate = False, then returns the logger