liveBook · Manning

Logging level

As explained in Python How-To

A logging level is a severity classification that determines which log records a logger or handler processes.

How can you keep routine events out of an urgent-error log without losing them elsewhere? Give log records severity levels, then set thresholds on the logger and its handlers. This makes a growing log easier to search when something goes wrong. section 12.2 section 12.2.2

Python’s logging levels rise in severity: DEBUG, INFO, WARNING, ERROR, and CRITICAL. They are integer constants valued 10 through 50 in steps of 10. A logger set to WARNING accepts WARNING, ERROR, and CRITICAL records, but not INFO or DEBUG records. Use CRITICAL when a failure affects functionality essential to normal operation. section 12.2.1 section 12.2.4

Keep a broad warning log and a narrow critical log

Set the logger to DEBUG so it can accept all five standard levels, then give its two file handlers different thresholds: import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) warning_handler = logging.FileHandler("warnings.log") warning_handler.setLevel(logging.WARNING) logger.addHandler(warning_handler) critical_handler = logging.FileHandler("critical.log") critical_handler.setLevel(logging.CRITICAL) logger.addHandler(critical_handler) logger.info("Task created") logger.warning("Task update delayed") logger.critical("Cannot update task status") The warning file receives the warning and critical messages; the critical file receives only the critical message. Neither receives the INFO message. section 12.2.2

The logger checks a record before sending it to any handler. A handler set to DEBUG therefore cannot recover an INFO record rejected by a logger set to WARNING. If handlers need different views, keep the logger’s threshold inclusive enough for both. Format retained records with a timestamp, level, module name, and message so important events are easier to find. section 12.2.5 section 12.2.3

How Python How-To covers it

How deep it goes
Works through numeric severity order, logger thresholds, separate handler thresholds, and the logger-first filtering rule.
Examples
Tests five severity messages against a WARNING threshold and splits file output into WARNING-and-above and CRITICAL-only records.
What it assumes
Builds on retrieving a logger and attaching handlers; defines the severity levels before configuring their thresholds.
What you can do after
Apply it via Python’s logging module to route records to files at different severity thresholds.
How it connects
Connects logging levels to loggers, file handlers, stream handlers, and log formatting.

Also explained in

Compare how 9 books explain logging level →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.