
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 (guildis the parent ofguild.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. Insideexcept,log.exception("...")also records the traceback.
Assignment
Write make_logger(name, stream, level="INFO") that:
- gets the logger
nameand sets its level - removes any handlers it already has (so calling it twice doesn't double every line)
- adds a
StreamHandler(stream)with the format"%(levelname)s %(name)s: %(message)s" - sets
propagate = False, then returns the logger
Write make_logger(name, stream, level="INFO") that:
- gets the logger
nameand sets its level - removes any handlers it already has (so calling it twice doesn't double every line)
- adds a
StreamHandler(stream)with the format"%(levelname)s %(name)s: %(message)s" - sets
propagate = False, then returns the logger
Press Run to try your code, then Check to test it.