A cross-platform Python library that adds colorful logging capabilities to the standard logging module
Project description
๐จ SmartLogger
Beautiful, colorful logging for Python with zero configuration
Transform your boring Python logs into beautiful, colorful masterpieces!
โจ Why SmartLogger?
Transform Your Logs Instantly!
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!
๐ Features
๐จ Beautiful ColorsEach log level gets its distinctive color:
|
โก Zero Configuration# That's it! Just one import
import smartlogger.auto
No setup, no configuration files, no complex initialization. It just works! |
๐ฅ๏ธ Universal Compatibility
|
๐ก๏ธ Production Ready
|
๐ฆ Installation
Choose your preferred method:
๐๏ธ Quick Installpip install pysmartlogger
|
๐ง From Sourcegit clone https://github.com/DeepPythonist/smartlogger.git
cd smartlogger
pip install .
|
๐ Quick Start
30-Second Setup
# 1. Your existing logging code
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# 2. Add this ONE line - that's it!
import smartlogger.auto
# 3. 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!")
Advanced Usage
๐๏ธ 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
import logging
import smartlogger.auto
# 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!")
๐จ Color Palette
| 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!" |
๐ Real-world Examples
๐ Web Application
import logging
import smartlogger.auto
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
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
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}")
๐ฅ๏ธ Compatibility Matrix
Tested and Verified โ
๐ Python Versions
|
๐ป Operating Systems
|
๐ง Development Tools
|
๐ Terminal Support
| 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 |
๐ฌ How It Works
The Magic Behind SmartLogger โจ
import smartlogger.auto
# This single import triggers the magic! ๐ช
๐ง 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! โก
๐ค Contributing
We love contributions! SmartLogger is an open-source project and we welcome contributions of all kinds.
๐ How to Contribute
Quick Start for Contributors
-
๐ด 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!
๐ฏ Areas We Need Help With
- ๐ Cross-platform testing (especially Windows variations)
- ๐จ New color schemes and themes
- ๐ Documentation improvements
- ๐ Bug reports and fixes
- ๐ก Feature suggestions
๐ Development Guidelines
- โ
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
โ FAQ
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.
๐ License
MIT License - see LICENSE file for details.
Feel free to use SmartLogger in your projects, both personal and commercial!
๐จโ๐ป Author
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pysmartlogger-1.2.6.tar.gz.
File metadata
- Download URL: pysmartlogger-1.2.6.tar.gz
- Upload date:
- Size: 23.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e429af0bbc38f090da4988ed7c76b41f6b8c1c93e538a69f5225312371a62393
|
|
| MD5 |
ceac1c5801a748eb280b0e5b9cf06fd0
|
|
| BLAKE2b-256 |
8e3256742a390a4a536f108b0f6c2a0b1c23c19b8d41986311734df7d57d49c7
|
File details
Details for the file pysmartlogger-1.2.6-py3-none-any.whl.
File metadata
- Download URL: pysmartlogger-1.2.6-py3-none-any.whl
- Upload date:
- Size: 13.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
12bdeef89426c904292a89726908e5a00df720c6b8edb347b0b68a8656f345cb
|
|
| MD5 |
c32515b600eaec281b83caa4582bd4f2
|
|
| BLAKE2b-256 |
dd2b47fdfa0ef95f96123f9ad2288862b83691a8dbeab83156f025f27d5a7312
|