A lightweight, synchronized Python logger with ANSI color support and automatic file rotation. Ported from a Golang logging utility to provide a clean, "tagged" logging experience for console and file-based output.
- 🎨 ANSI Styling: Full support for foreground, background, and font styles (Bold, Italic, etc.).
- 🏷️ Tagged Logs: Every log entry includes a fixed-width tag (7 characters) for easy visual alignment.
- 📂 File Rotation: Background thread support to rotate logs at a specific time (e.g., daily at midnight).
- 🚀 Synchronous & Simple: Built for reliability and ease of use in Python scripts and applications.
You can install the library via pip:
pip install nba-logfrom nba_log import Logger
# Initialize with a tag and debug mode enabled
log = Logger("GPIO", debug_mode=True)
# Apply standard colors (Info: White, Warn: Yellow, Error: Red, etc.)
log.set_default_style()
log.info("System initialized")
log.debug("Checking sensors...") # Only visible if debug_mode=True
log.error("Failed to reach server")Enable persistent logging to a directory. The logger will automatically append the date to the filename.
import time
from nba_log import Logger
# 1. Setup Logger
log = Logger("SERVER", debug_mode=True)
log.set_default_style()
# 2. Enable file writing (Directory Path, File Prefix)
log.set_write_files_enable("./logs", "api_service")
# 3. Schedule rotation at 00:00 (Midnight)
# The logger handles the timing in the background
log.change_file_routine(0, 0)
log.info("Continuous logging started. Press Ctrl+C to stop.")
try:
# 4. Infinite loop to print every 1 minute
while True:
log.info("Heartbeat: Service is healthy")
# Wait for 5 seconds
time.sleep(5)
except KeyboardInterrupt:
log.warn("Logging stopped by user.")You can override default styles using the provided constants. Styles are lists of ANSI codes.
from nba_log import Logger, StyleFgYellow, StyleFontBold, StyleBgRed
log = Logger("APP", True)
# Custom style for warnings: Bold and Yellow text
log.warn_style = [StyleFontBold, StyleFgYellow]
# Custom style for fatal errors: Bold black text on a Red background
log.fatal_style = [StyleFontBold, StyleBgRed]
log.warn("This is a custom warning style!")