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

  1. Import logging and configure the basic setup with logging.basicConfig().
  2. Create a logger: logger = logging.getLogger(__name__).
  3. 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=True in 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 % or f-strings in log messages is not deferred; use %s style with arguments for lazy evaluation in performance-critical paths.