Definition
A declarative way to record events that occur while a program is running, providing a permanent “breadcrumb trail” of state and logic transitions.
Why It Matters
Logging is the ‘black box’ of software; without a rigorous logging strategy, developers are blind to the root causes of intermittent failures in production, leading to wasted hours and decreased system reliability.
Core Concepts
- Logging Levels (In order of severity):
DEBUG: Smallest details; used for diagnosing problems.INFO: Confirmation that things are working as expected.WARNING: Something unexpected happened, but the program is still working.ERROR: The program could not perform a specific function.CRITICAL: A serious error; the program itself may be unable to continue.
logging.basicConfig(): Configures the logger (level, format, and optional filename).logging.disable(logging.CRITICAL): Disables all logging calls of a certain level and below. This allows you to toggle all “debug prints” on or off with a single line.- Logging vs. print(): Logging is superior because it includes timestamps, is easily categorized, and can be silenced without deleting the code.
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.error('An error occurred')