Introduction to logging in Python
A gentle, practical introduction to logging in Python
Why bother with a dedicated logging library?
- Prints don’t scale.
print()is fine during quick experiments, but real programs need a record that can be filtered, rotated, or shipped elsewhere. - Separation of concerns. You decide what to log in your code;
loggingdecides where and how to write it (console, file, etc.). - Built-in, no extra dependency. The standard library’s
loggingmodule is powerful enough for most applications.
Core concepts
| Concept | Role in the ecosystem | Typical examples |
|---|---|---|
| Logger | The entry point your code calls (logger.info(...)). You can have many, one per module. | "__main__", "my_package.worker" |
| Handler | Decides where the record goes. | StreamHandler (stdout), FileHandler, TimedRotatingFileHandler, SMTPHandler |
| Formatter | Decides how the record looks. | '%(asctime)s - %(levelname)s - %(name)s - %(message)s' |
A minimal logger
import logging
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s | %(message)s"
)
logging.info("Hello, world!")basicConfigis a one-liner good for small scripts.- In bigger projects, mixing multiple modules / log files, you’ll want finer control.
Rotating files at midnight
Rotating a log file means creating a new log file after a certain time or size limit is reached. In this case, a new file is created every night at midnight. Only the most recent two log files are kept—yesterday’s and today’s—while older ones are deleted automatically.