How do I use the logging module instead of print()?
· Category: Python Programming
Short answer
The logging module provides a flexible framework for emitting log messages with severity levels. Unlike print(), it supports configurable outputs, formatting, and filtering without changing application code.
Steps
- Import
loggingand configure the basic setup withlogging.basicConfig(). - Create a logger:
logger = logging.getLogger(__name__). - Emit messages:
logger.info("Message"),logger.error("Error"), etc.
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
)
logger = logging.getLogger(__name__)
def divide(a, b):
logger.debug(f"Dividing {a} by {b}")
try:
return a / b
except ZeroDivisionError:
logger.error("Division by zero", exc_info=True)
return None
divide(10, 2)
divide(10, 0)
Tips
- Use
__name__for logger names to create a hierarchy that mirrors your package structure. - Configure handlers (StreamHandler, FileHandler, RotatingFileHandler) for different destinations.
- Use
exc_info=Truein error logs to include stack traces. - Set levels per logger or handler for fine-grained control.
Common issues
- Calling
logging.basicConfig()after other logging setup has occurred may have no effect. - Using the root logger directly (
logging.info()) in libraries interferes with application logging configuration. - String formatting with
%orf-stringsin log messages is not deferred; use%sstyle with arguments for lazy evaluation in performance-critical paths.