Sub topic 1
Why Use Logging Instead of `print`
Prerequisites
Assume you know basic Python syntax, functions, modules, try/except, and how to run a script from a terminal. You should also recognize classes and inheritance.
Why Use Logging Instead of `print`
print() writes immediately to standard output. It is useful for quick debugging, but application diagnostics need more control. The logging module lets you classify events, include timestamps and logger names, route records to different destinations, and change verbosity without editing every call.
Prefer parameterized logging calls:
logger.info("User %s logged in", username)The message arguments are combined only if the record is actually emitted. With an f-string, the string is built before logging decides whether the message should be discarded. Logging also supports handlers for consoles, files, queues, and monitoring systems.
Log Levels: `DEBUG` to `CRITICAL`
Levels communicate severity:
| Level | Use |
|---|---|
| `DEBUG` | Detailed information for diagnosing behavior |
| `INFO` | Normal progress and significant state changes |
| `WARNING` | An unusual condition that does not stop the operation |
| `ERROR` | An operation failed |
| `CRITICAL` | A severe failure requiring immediate attention |
A configured threshold allows that level and more severe levels through. For example, an INFO threshold emits INFO, WARNING, ERROR, and CRITICAL, but drops DEBUG.
Getting Started with `basicConfig`
basicConfig() provides simple root-logger configuration. It has no effect after logging has already been configured, so call it near the program's entry point.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("Starting application")
logger.debug("This is hidden at INFO level")The default stream is usually standard error, not standard output. Use level=logging.DEBUG when diagnosing a problem, but avoid enabling detailed logs permanently if they expose sensitive data or create excessive volume.
Named Loggers with `getLogger`
logging.getLogger(name) returns a named logger. A module commonly uses logging.getLogger(__name__), which gives records a name matching the module's import path. Names form a hierarchy, such as myapp and myapp.database; this supports separate configuration while allowing records to propagate to ancestor handlers.
Exercise
At an INFO threshold, which call is discarded: logger.debug("cache miss") or logger.warning("cache is slow")?
Show answer
logger.debug("cache miss") is discarded. The WARNING record is emitted.