Principle:Obss Sahi Logging
| Knowledge Sources | |
|---|---|
| Domains | Infrastructure, Logging |
| Last Updated | 2026-02-08 12:00 GMT |
Overview
Design pattern for structured, leveled logging with custom log levels and color-coded console output in a Python library.
Description
Library-level Logging provides a centralized logging infrastructure that extends Python's standard logging module with custom log levels and formatters. The key design decisions are: defining a custom PKG_INFO level for package metadata messages, using ANSI escape codes for color-coded terminal output by severity, and providing a pre-configured logger instance that respects environment variables for debug toggling. This avoids ad-hoc print statements and enables users to control log verbosity.
Usage
Apply this principle when building a library that needs structured diagnostic output with different severity levels, custom message formatting per level, and environment-variable-based debug activation.
Theoretical Basis
The pattern builds on Python's logging hierarchy:
- Custom levels: Insert between standard levels (e.g., INFO < PKG_INFO < WARNING) for domain-specific messages
- Logger class replacement: Use logging.setLoggerClass() to ensure all library loggers support custom methods
- Formatter per level: Map each level to distinct ANSI color codes for visual scanning
- Environment toggle: Check environment variables at import time to set appropriate levels