
The logging module provides proper logging with levels, formatting, and output control.
Basic setup:
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(message)s"
)
logging.debug("Debug info") # development detail
logging.info("App started") # general info
logging.warning("Low disk space") # unexpected but OK
logging.error("Database error") # serious problem
logging.critical("System crash") # fatalLog levels (lowest to highest): DEBUG < INFO < WARNING < ERROR < CRITICAL
Logging to file:
logging.basicConfig(
filename="app.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s"
)Logger per module:
logger = logging.getLogger(__name__)
logger.info("This module started")Why not print: Logging has levels (easily turn off debug in production), timestamps, source info, and can write to files, email, or services simultaneously.
Reference:
TaskLoco™ — The Sticky Note GOAT