Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Standard library & toolingMiddleVery commonPractical

Why is the `logging` module preferred over scattered `print()` statements for diagnostic output in real applications?

Answer

`logging` gives each message a severity level (`DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`) so verbosity can be tuned per environment without touching source code, routes messages independently to multiple destinations (console, rotating files, remote log aggregators) through configurable handlers, and includes structured context like timestamps, logger name and module automatically. `print()` has none of that structure out of the box: by default it writes to stdout with no severity levels, no handler routing, and no automatic context, and while `print(..., file=sys.stderr)` can redirect a single call, or a shell can redirect stdout entirely, neither gives you `logging`'s independently configurable per-message levels and destinations. That gap in structure — not the mere absence of any redirection at all — is why `print()` statements are typically left behind as debugging clutter that has to be manually found and removed, while `logging` calls stay useful in production.

Strong answer includes

  • severity levels let verbosity be tuned per environment without code changes
  • handlers route messages to multiple destinations independently
  • print() can redirect its output but still lacks logging's per-message levels, handler routing, and automatic context

Practical example

Python example
logging.getLogger(__name__).warning("retrying %s after %s", url, error)

can be silenced in production by raising the root logger's level to `ERROR` , without deleting or commenting out a single line of code.

#logging#diagnostics

Sources

logging — Logging facility for PythonPython Software Foundation · Loggers, handlers, levels and structured diagnostic output