Sub topic 1
Why Use logging Instead of print
A script that prints progress messages works until you need to run it somewhere else. In a service, a scheduled job, or a library used by other people, print gives you no control over what is shown or where it goes. The logging module in the standard library solves this. This chapter shows what you gain from it and the first mistakes to avoid.
Prerequisites
- Basic Python syntax, functions, and modules.
- Running scripts from a terminal.
- Using
try/except(needed in later chapters, not this one).
What print cannot do
print writes text to standard output. That is all it does. Once a program grows, you run into these limits:
- You cannot turn debug messages off without editing or deleting code.
- Messages carry no severity, so a routine step looks the same as a failure.
- There is no timestamp or source name unless you add them by hand at every call.
- Output goes to one place. Sending it to a file as well means changing every call.
- Normal output and diagnostics share the same stream, so they mix when you pipe or redirect.
The same message with logging
Here is a minimal setup using basicConfig, which later chapters cover in detail.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("Starting %s", "app")
logger.debug("This message is not shown because the level is INFO")The INFO message is printed to stderr with a timestamp, its severity, and the logger name. The DEBUG message is dropped because the threshold is INFO. To see it, change level to logging.DEBUG. The calls in your code stay the same.
Notice that the message and its values are passed separately: "Starting %s", "app". The module builds the final string only if the record is actually emitted. A message that is filtered out costs almost nothing.
What a log call gives you
| Need | logging | |
|---|---|---|
| Hide noisy messages | Edit or delete calls | Raise the level |
| Mark severity | Write it in the text | Use `debug`, `info`, `warning`, `error`, `critical` |
| Add time and source | Format by hand | Set a format once |
| Write to a file and the console | Change every call | Add handlers |
| Keep diagnostics apart from output | Not possible | Logs go to stderr by default |
How a log call works
A log call creates a record. The record is checked against a level, then passed to handlers that format it and send it somewhere.
Each box in this flow becomes its own chapter. For now, remember the main idea: your code says what happened, and configuration decides what to do about it.
Common errors
- Seeing no output. Without configuration, the default threshold is WARNING, so
logger.info(...)prints nothing. CallbasicConfigor set a level. - Formatting the message yourself.
logger.info(f"User {name}")builds the string even when the record is dropped. Preferlogger.info("User %s", name). - Keeping
printfor diagnostics. It cannot be filtered later. Useprintfor the real output of a command-line tool andloggingfor everything about how the program is running.
Exercise
A script calls logger.info("Loaded %d rows", 10) after only calling logging.getLogger(_name_), with no basicConfig and no handlers. Nothing appears on the terminal. Why, and what is the smallest change that makes the message appear?
Show answer
The effective level is the default WARNING, so the INFO record is dropped. Adding logging.basicConfig(level=logging.INFO) at the start of the script lowers the threshold and also installs a stderr handler, so the message appears.