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-0610:30:45-myapp-DEBUG-Processinguserdata...
2024-01-0610:30:45-myapp-INFO-Userauthenticatedsuccessfully2024-01-0610:30:45-myapp-WARNING-APIratelimitapproaching2024-01-0610:30:45-myapp-ERROR-Databaseconnectionfailed2024-01-0610:30:45-myapp-CRITICAL-SystemshuttingdownAfter SmartLogger:
importsmartlogger.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:
| importloggingimportsmartlogger.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.automust be imported immediately after importingloggingand before any logging configuration or usage.
# 1. Import logging firstimportlogging# 2. Import SmartLogger IMMEDIATELY after logging (THIS IS CRITICAL!)importsmartlogger.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!")importloggingimportsmartlogger.auto# ← Right after logging!logging.basicConfig()
logger=logging.getLogger(__name__)
logger.info("✅ Colors work!") | importlogginglogging.basicConfig() # ← Configuration before SmartLoggerimportsmartlogger.auto# ← Too late!logger=logging.getLogger(__name__)
logger.info("❌ No colors...") |
🎛️ Custom Configuration
importloggingfromsmartlogger.core.formatterimportColorFormatterfromsmartlogger.core.handlerimportColorHandler# Create a custom logger with SmartLoggerlogger=logging.getLogger('my_custom_app')
logger.setLevel(logging.DEBUG)
# Use SmartLogger's handler and formatterhandler=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!importloggingimportsmartlogger.auto# ← Must be imported before any logging configuration!# Now configure your existing enterprise logging setupLOGGING_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
importloggingimportsmartlogger.auto# ← Immediately after logging import!fromflaskimportFlaskapp=Flask(__name__)
logger=logging.getLogger('webapp')
@app.route('/users/<user_id>')defget_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}")
returnuser.to_json()
exceptUserNotFound:
logger.warning(f"⚠️ User {user_id} not found in database")
return {"error": "User not found"}, 404exceptDatabaseErrorase:
logger.error(f"❌ Database error: {e}")
return {"error": "Internal server error"}, 500🤖 Machine Learning Pipeline
importloggingimportsmartlogger.auto# ← Import right after logging!logger=logging.getLogger('ml_pipeline')
deftrain_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")
iflen(data) <1000:
logger.warning(f"⚠️ Small dataset detected ({len(data)} samples)")
model=train_neural_network(data)
accuracy=evaluate_model(model)
ifaccuracy>0.95:
logger.info(f"🎯 Excellent model performance: {accuracy:.2%}")
elifaccuracy>0.80:
logger.warning(f"📈 Good model performance: {accuracy:.2%}")
else:
logger.error(f"📉 Poor model performance: {accuracy:.2%}")
exceptExceptionase:
logger.critical(f"🚨 Model training failed: {e}")
raise📊 Data Processing
importloggingimportsmartlogger.auto# ← Critical: Import immediately after logging!importpandasaspdlogger=logging.getLogger('data_processor')
defprocess_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 validationmissing_data=df.isnull().sum().sum()
ifmissing_data>0:
logger.warning(f"⚠️ Found {missing_data} missing values")
# Process datacleaned_df=clean_data(df)
logger.info(f"✅ Data cleaning completed: {cleaned_df.shape}")
# Save resultscleaned_df.to_csv('processed_data.csv')
logger.info("💾 Processed data saved successfully")
exceptFileNotFoundError:
logger.error(f"❌ Data file not found: {file_path}")
exceptpd.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 |
importloggingimportsmartlogger.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 Detectiondefdetect_color_support():
"""Detects if the current environment supports ANSI colors"""# Checks terminal type, environment variables, IDE supportreturnis_terminal_supports_color()
# 2. 🎨 Smart Color Applicationdefapply_colors(log_record):
"""Applies appropriate colors based on log level"""ifnotsupports_colors:
returnoriginal_format(log_record)
color=get_color_for_level(log_record.levelname)
returnf"{color}{log_record.levelname}{RESET}"# 3. 🔄 Safe Monkey-Patchingdefpatch_logging():
"""Safely patches logging without breaking existing code"""original_formatter=logging.Formatterlogging.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
blackfor formatting - 🧪 Testing: Add tests for new features
- 📝 Documentation: Update README for new features
- 🔍 Type hints: Use type annotations where possible
importlogginglogging.basicConfig(level=logging.INFO)
logger=logging.getLogger(__name__)
# Too late! SmartLogger can't patch existing configimportsmartlogger.autoResult: No colors, plain text logging | # Missing: import loggingimportsmartlogger.autologging.basicConfig(level=logging.INFO) logger=logging.getLogger(__name__)Result: Import error or unexpected behavior |
importlogging# Configuration happens firstlogging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().addHandler(handler)
importsmartlogger.auto# Too late!Result: SmartLogger can't enhance existing loggers | importloggingimportsmartlogger.auto# Perfect timing!# All configuration after SmartLoggerlogging.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 afterlogging and before any logging configuration to work properly:
# ✅ CORRECT ORDERimportloggingimportsmartlogger.auto# ← Must be here!logging.basicConfig() # ← Configuration after SmartLogger# ❌ WRONG ORDER importlogginglogging.basicConfig() # ← Configuration before SmartLoggerimportsmartlogger.auto# ← Too late! Colors won't workQ: 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:
fromsmartlogger.config.colorsimportColors# Customize colorsColors.INFO=Colors.CYAN# Make INFO messages cyanColors.DEBUG=Colors.MAGENTA# Make DEBUG messages magentaQ: 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!

