Logging in Python
A structured, leveled way for real programs to report what they are doing
logging module lets your program emit a stream of timestamped, categorised messages. Unlike print(), each message carries a severity level, can be routed to several destinations at once (console, file, network), and can be turned up or down without editing your code. Logging is how intermediate-scale and production programs tell you what happened, when, and how bad it was.
- explain why
print()stops scaling as a debugging tool, - choose the right one of the five log levels,
- get a named logger and understand the root logger,
- attach handlers and formatters to send logs to the console and to a file,
- record exceptions with a full traceback using
logger.exception.
1. Why print() is not enough
When you were learning the language, print() was the natural way to peek at what your code was doing. It works, but it has no notion of importance and no built-in structure. Every message is equal, they all go to standard output, and to silence them you have to physically delete or comment out lines.
A real program needs to answer questions like: What routine information happened? What warnings did we survive? What errors actually broke something? With print() you cannot tell these apart, and you certainly cannot say "show me warnings and worse in production, but everything while I debug" without rewriting code.
| Concern | print() | logging |
|---|---|---|
| Severity of a message | none, all equal | five levels |
| Where output goes | always stdout | any handlers you attach |
| Turn messages off | edit the code | change one level setting |
| Timestamp and source | you add it by hand | the formatter adds it |
| Show a full traceback | manual | exc_info / exception() |
Logging keeps the convenience of "print a message" while adding the control a growing program needs.