🐍 Python Intermediate

What is logging in Python?

Answer

Python's logging module provides a flexible, production-ready logging system. Five severity levels: DEBUG, INFO, WARNING (default threshold), ERROR, CRITICAL. Basic usage: import logging; logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"); logging.info("App started"). Use named loggers for per-module control: logger = logging.getLogger(__name__). Handlers control where logs go: StreamHandler (console), FileHandler, RotatingFileHandler, SMTPHandler. Formatters control the format. Filters control which records pass through. Configure via dict: logging.config.dictConfig(config). Best practice: use logging.exception() in except blocks to include the full stack trace automatically. Avoid print() for debugging in production — use logging with appropriate levels.