Andromeda
Note

Logging (Python)

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):
    1. DEBUG: Smallest details; used for diagnosing problems.
    2. INFO: Confirmation that things are working as expected.
    3. WARNING: Something unexpected happened, but the program is still working.
    4. ERROR: The program could not perform a specific function.
    5. 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')

Connected Concepts