Back to results for “Exception Handling”
Python › Logging

Why should you use the logging module instead of print() for diagnostic output?

Beginner

Answer

logging supports severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), can be routed to multiple destinations (console, files, network) simultaneously, includes timestamps and context automatically, and can be toggled or filtered without editing code -- print() offers none of this and is hard to disable in production.
import logging

logging.basicConfig(level=logging.INFO)
logging.info('Application started')
logging.warning('Config value missing, using default')
Real-world example A production web service logs request errors to a file and sends CRITICAL-level logs to a monitoring alert system, something print() statements can't do.

Common follow-ups: What are the five standard logging levels in order?;How do you disable logging below a certain level?