The logging module is Python's standard library facility for recording diagnostic messages. It provides five severity levels: DEBUG (detailed diagnostic), INFO (confirmation of expected events), WARNING (something unexpected), ERROR (a serious problem), and CRITICAL (a fatal condition). Messages at or above the configured level are processed; lower-level messages are silently discarded.
The basic usage is straightforward: import logging; logging.warning("Something happened"). For production applications, you configure loggers, handlers (where messages go — console, file, network), formatters (how messages look), and filters (which messages pass). The logging hierarchy mirrors the module hierarchy: the logger named "myapp.models" inherits settings from "myapp", which inherits from the root logger.
logging replaces print() statements for diagnostics because it provides configurable severity levels, output destinations, message formatting, and the ability to enable or disable messages without modifying code. The module uses lazy formatting (logging.info("Processing %s", name)) to avoid string formatting overhead when the message level is disabled. For modern Python, the logging module remains the standard; third-party alternatives like loguru offer simpler APIs but less integration with the broader ecosystem.
Discussed in:
- Chapter 11: Error Handling — Warnings and Logging