Beautiful, colorful logging for Python with zero configuration
Transform your boring Python logs into beautiful, colorful masterpieces!
Just one line of code transforms boring logs into beautiful, colorful masterpieces!
Before SmartLogger:
2024-01-06 10:30:45 - myapp - DEBUG - Processing user data...
2024-01-06 10:30:45 - myapp - INFO - User authenticated successfully
2024-01-06 10:30:45 - myapp - WARNING - API rate limit approaching
2024-01-06 10:30:45 - myapp - ERROR - Database connection failed
2024-01-06 10:30:45 - myapp - CRITICAL - System shutting down
After SmartLogger:
import smartlogger.auto # One line = Colorful logs! π¨
Your logs instantly become beautiful and easy to read with distinctive colors for each level!
Each log level gets its distinctive color:
|
import logging
import smartlogger.auto # β Right after logging! No setup, no configuration files, no complex initialization. Just remember the import order! |
|
|
pip install pysmartlogger |
git clone https://github.com/DeepPythonist/smartlogger.git
cd smartlogger
pip install . |
β οΈ IMPORTANT: Import Order Matters!
smartlogger.auto
must be imported immediately after importinglogging
and before any logging configuration or usage.
# 1. Import logging first
import logging
# 2. Import SmartLogger IMMEDIATELY after logging (THIS IS CRITICAL!)
import smartlogger.auto
# 3. Now configure your logging (BasicConfig, handlers, etc.)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# 4. Your logs are now colorful! π¨
logger.debug("π Debug: Investigating user behavior")
logger.info("β
Info: User login successful")
logger.warning("β οΈ Warning: API rate limit at 80%")
logger.error("β Error: Payment processing failed")
logger.critical("π¨ Critical: Database connection lost!")
import logging
import smartlogger.auto # β Right after logging!
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.info("β
Colors work!") |
import logging
logging.basicConfig() # β Configuration before SmartLogger
import smartlogger.auto # β Too late!
logger = logging.getLogger(__name__)
logger.info("β No colors...") |
ποΈ Custom Configuration
import logging
from smartlogger.core.formatter import ColorFormatter
from smartlogger.core.handler import ColorHandler
# Create a custom logger with SmartLogger
logger = logging.getLogger('my_custom_app')
logger.setLevel(logging.DEBUG)
# Use SmartLogger's handler and formatter
handler = ColorHandler()
formatter = ColorFormatter(
'%(asctime)s | %(name)s | %(levelname)s | %(message)s'
)
handler.setFormatter(formatter)
logger.addHandler(handler)
# Your beautiful custom logs!
logger.info("π¨ Custom formatting with colors!")
π’ Enterprise Integration
# β οΈ Remember: Import order is critical!
import logging
import smartlogger.auto # β Must be imported before any logging configuration!
# Now configure your existing enterprise logging setup
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'default': {
'level': 'INFO',
'formatter': 'standard',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'INFO',
'propagate': False
}
}
}
logging.config.dictConfig(LOGGING_CONFIG)
# SmartLogger automatically enhances ALL your existing loggers!
logger = logging.getLogger('enterprise.module')
logger.info("π’ Enterprise logging is now colorful!")
Log Level | Color | Visual | Use Case | Example |
---|---|---|---|---|
π΅ DEBUG | Blue | π |
Development & debugging | "Processing user input: email@example.com" |
π’ INFO | Green | βΉοΈ |
General information | "User authenticated successfully" |
π‘ WARNING | Yellow | β οΈ |
Potential issues | "API rate limit approaching (80%)" |
π΄ ERROR | Red | β |
Actual errors | "Failed to connect to database" |
π₯ CRITICAL | Bright Red + Bold | π¨ |
Urgent attention needed | "System memory critically low!" |
π Web Application
import logging
import smartlogger.auto # β Immediately after logging import!
from flask import Flask
app = Flask(__name__)
logger = logging.getLogger('webapp')
@app.route('/users/<user_id>')
def get_user(user_id):
logger.info(f"π Fetching user data for ID: {user_id}")
try:
user = database.get_user(user_id)
logger.info(f"β
User found: {user.email}")
return user.to_json()
except UserNotFound:
logger.warning(f"β οΈ User {user_id} not found in database")
return {"error": "User not found"}, 404
except DatabaseError as e:
logger.error(f"β Database error: {e}")
return {"error": "Internal server error"}, 500
π€ Machine Learning Pipeline
import logging
import smartlogger.auto # β Import right after logging!
logger = logging.getLogger('ml_pipeline')
def train_model(dataset_path):
logger.info(f"π Starting model training with dataset: {dataset_path}")
try:
data = load_dataset(dataset_path)
logger.info(f"π Dataset loaded: {len(data)} samples")
if len(data) < 1000:
logger.warning(f"β οΈ Small dataset detected ({len(data)} samples)")
model = train_neural_network(data)
accuracy = evaluate_model(model)
if accuracy > 0.95:
logger.info(f"π― Excellent model performance: {accuracy:.2%}")
elif accuracy > 0.80:
logger.warning(f"π Good model performance: {accuracy:.2%}")
else:
logger.error(f"π Poor model performance: {accuracy:.2%}")
except Exception as e:
logger.critical(f"π¨ Model training failed: {e}")
raise
π Data Processing
import logging
import smartlogger.auto # β Critical: Import immediately after logging!
import pandas as pd
logger = logging.getLogger('data_processor')
def process_customer_data(file_path):
logger.info(f"π Processing customer data from: {file_path}")
try:
df = pd.read_csv(file_path)
logger.debug(f"π Raw data shape: {df.shape}")
# Data validation
missing_data = df.isnull().sum().sum()
if missing_data > 0:
logger.warning(f"β οΈ Found {missing_data} missing values")
# Process data
cleaned_df = clean_data(df)
logger.info(f"β
Data cleaning completed: {cleaned_df.shape}")
# Save results
cleaned_df.to_csv('processed_data.csv')
logger.info("πΎ Processed data saved successfully")
except FileNotFoundError:
logger.error(f"β Data file not found: {file_path}")
except pd.errors.EmptyDataError:
logger.critical(f"π¨ Data file is empty: {file_path}")
|
|
|
Terminal | Windows | macOS | Linux | Notes |
---|---|---|---|---|
Windows Terminal | β | - | - | Full color support |
PowerShell | β | β | β | Core & 7+ |
Command Prompt | β | - | - | Windows 10+ |
iTerm2 | - | β | - | Recommended for macOS |
Terminal.app | - | β | - | Built-in macOS terminal |
bash/zsh/fish | β | β | β | Universal support |
import logging
import smartlogger.auto # β This triggers the magic! πͺ
# IMPORTANT: Must be imported right after logging and before any configuration!
π§ Technical Implementation
SmartLogger uses intelligent monkey-patching to enhance Python's logging module:
# 1. π΅οΈ Environment Detection
def detect_color_support():
"""Detects if the current environment supports ANSI colors"""
# Checks terminal type, environment variables, IDE support
return is_terminal_supports_color()
# 2. π¨ Smart Color Application
def apply_colors(log_record):
"""Applies appropriate colors based on log level"""
if not supports_colors:
return original_format(log_record)
color = get_color_for_level(log_record.levelname)
return f"{color}{log_record.levelname}{RESET}"
# 3. π Safe Monkey-Patching
def patch_logging():
"""Safely patches logging without breaking existing code"""
original_formatter = logging.Formatter
logging.Formatter = EnhancedColorFormatter
# Maintains 100% backward compatibility!
Key Features:
- π Smart Detection: Automatically detects color support
- π‘οΈ Safe Patching: Won't break existing logging configurations
- β‘ Performance: Minimal overhead (~0.1ms per log message)
- π Reversible: Can be disabled at runtime if needed
π― Zero Dependencies Philosophy
SmartLogger is built with zero external dependencies by design:
- π¦ Pure Python: Only uses standard library modules
- π Fast Installation: No compilation or external packages
- π Secure: No third-party code vulnerabilities
- π± Lightweight: Total package size < 50KB
# Compare installation times:
pip install some-logging-lib # Downloads 20+ dependencies π΄
pip install pysmartlogger # Just SmartLogger! β‘
We love contributions! SmartLogger is an open-source project and we welcome contributions of all kinds.
π How to Contribute
-
π΄ Fork the repository
git clone https://github.com/DeepPythonist/smartlogger.git cd smartlogger
-
π Create a feature branch
git checkout -b feature/amazing-new-feature
-
π§ͺ Run tests
python -m pytest tests/ -v python demo_smartlogger.py
-
π Make your changes and commit
git add . git commit -m "β¨ Add amazing new feature"
-
π Push and create PR
git push origin feature/amazing-new-feature # Then create a Pull Request on GitHub!
- π Cross-platform testing (especially Windows variations)
- π¨ New color schemes and themes
- π Documentation improvements
- π Bug reports and fixes
- π‘ Feature suggestions
- β
Code style: We use
black
for formatting - π§ͺ Testing: Add tests for new features
- π Documentation: Update README for new features
- π Type hints: Use type annotations where possible
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Too late! SmartLogger can't patch existing config
import smartlogger.auto Result: No colors, plain text logging |
# Missing: import logging
import smartlogger.auto
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) Result: Import error or unexpected behavior |
import logging
# Configuration happens first
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().addHandler(handler)
import smartlogger.auto # Too late! Result: SmartLogger can't enhance existing loggers |
import logging
import smartlogger.auto # Perfect timing!
# All configuration after SmartLogger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("π¨ Beautiful colors!") Result: Beautiful, colorful logs! |
Q: Why is import order important?
A: SmartLogger uses monkey-patching to enhance Python's logging module. It must be imported immediately after logging
and before any logging configuration to work properly:
# β
CORRECT ORDER
import logging
import smartlogger.auto # β Must be here!
logging.basicConfig() # β Configuration after SmartLogger
# β WRONG ORDER
import logging
logging.basicConfig() # β Configuration before SmartLogger
import smartlogger.auto # β Too late! Colors won't work
Q: Does SmartLogger affect performance?
A: Minimal impact! SmartLogger adds ~0.1ms overhead per log message. Color detection is cached, so there's virtually no performance penalty after initialization.
Q: Can I use SmartLogger in production?
A: Absolutely! SmartLogger is designed for production use:
- π‘οΈ Safe: Won't break existing logging
- π Zero dependencies: No external vulnerabilities
- β‘ Performance optimized: Minimal overhead
- π Reversible: Can be disabled if needed
Q: What if my terminal doesn't support colors?
A: SmartLogger automatically detects color support and gracefully falls back to plain text in non-color environments. No configuration needed!
Q: Can I customize the colors?
A: Yes! You can customize colors using the advanced configuration:
from smartlogger.config.colors import Colors
# Customize colors
Colors.INFO = Colors.CYAN # Make INFO messages cyan
Colors.DEBUG = Colors.MAGENTA # Make DEBUG messages magenta
Q: Does it work with existing logging configurations?
A: Yes! SmartLogger is designed to work seamlessly with existing logging setups. Just add import smartlogger.auto
and your existing loggers become colorful.
MIT License - see LICENSE file for details.
Feel free to use SmartLogger in your projects, both personal and commercial!