Skip to content

🎨 Beautiful, colorful logging for Python with zero configuration. Transform boring logs into colorful masterpieces instantly!

License

Notifications You must be signed in to change notification settings

DeepPythonist/smartlogger

Repository files navigation

🎨 SmartLogger

Beautiful, colorful logging for Python with zero configuration

PyPI version Python versions Downloads License: MIT Code style: black

Transform your boring Python logs into beautiful, colorful masterpieces!


✨ Why SmartLogger?

Transform Your Logs Instantly!

SmartLogger Before and After

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 Colors

Each log level gets its distinctive color:

  • πŸ”΅ DEBUG - Blue (development info)
  • 🟒 INFO - Green (general info)
  • 🟑 WARNING - Yellow (potential issues)
  • πŸ”΄ ERROR - Red (actual errors)
  • πŸ”₯ CRITICAL - Bright Red + Bold (urgent!)

⚑ Zero Configuration

import logging
import smartlogger.auto  # ← Right after logging!

No setup, no configuration files, no complex initialization. Just remember the import order!

πŸ–₯️ Universal Compatibility

  • βœ… Windows (CMD, PowerShell, Windows Terminal)
  • βœ… macOS (Terminal, iTerm2)
  • βœ… Linux (bash, zsh, fish)
  • βœ… IDEs (VS Code, PyCharm, Jupyter)
  • βœ… Python 3.8+

πŸ›‘οΈ Production Ready

  • πŸš€ Zero dependencies - No external packages required
  • ⚑ Performance optimized - Minimal overhead
  • πŸ”’ Safe - Won't break existing logging code
  • 🧠 Smart detection - Auto-detects color support

πŸ“¦ Installation

Choose your preferred method:

🏎️ Quick Install

pip install pysmartlogger

πŸ”§ From Source

git clone https://github.com/DeepPythonist/smartlogger.git
cd smartlogger
pip install .

πŸš€ Quick Start

30-Second Setup

⚠️ IMPORTANT: Import Order Matters!
smartlogger.auto must be imported immediately after importing logging 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!")

βœ… Correct Import Order vs ❌ Wrong Import Order

βœ… CORRECT

import logging
import smartlogger.auto  # ← Right after logging!

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.info("βœ… Colors work!")

❌ WRONG

import logging
logging.basicConfig()  # ← Configuration before SmartLogger
import smartlogger.auto  # ← Too late!

logger = logging.getLogger(__name__)
logger.info("❌ No colors...")

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
# ⚠️ 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!")

🎨 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  # ← 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}")

πŸ–₯️ Compatibility Matrix

Tested and Verified βœ…

🐍 Python Versions

  • βœ… Python 3.8
  • βœ… Python 3.9
  • βœ… Python 3.10
  • βœ… Python 3.11
  • βœ… Python 3.12

πŸ’» Operating Systems

  • βœ… Windows 10/11
  • βœ… macOS (Intel & Apple Silicon)
  • βœ… Linux (Ubuntu, CentOS, Alpine)
  • βœ… Docker containers
  • βœ… Cloud environments

πŸ”§ Development Tools

  • βœ… VS Code (+ extensions)
  • βœ… PyCharm (Pro & Community)
  • βœ… Jupyter Notebooks
  • βœ… Google Colab
  • βœ… Terminal/CMD/PowerShell

🌐 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 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! ⚑

🀝 Contributing

We love contributions! SmartLogger is an open-source project and we welcome contributions of all kinds.

πŸš€ How to Contribute

Quick Start for Contributors

  1. 🍴 Fork the repository

    git clone https://github.com/DeepPythonist/smartlogger.git
    cd smartlogger
  2. 🌟 Create a feature branch

    git checkout -b feature/amazing-new-feature
  3. πŸ§ͺ Run tests

    python -m pytest tests/ -v
    python demo_smartlogger.py
  4. πŸ“ Make your changes and commit

    git add .
    git commit -m "✨ Add amazing new feature"
  5. πŸš€ 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 black for formatting
  • πŸ§ͺ Testing: Add tests for new features
  • πŸ“ Documentation: Update README for new features
  • πŸ” Type hints: Use type annotations where possible

⚠️ Common Mistakes

🚫 Avoid These Import Order Mistakes!

❌ MISTAKE 1: Late Import

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

❌ MISTAKE 2: Missing logging import

# Missing: import logging
import smartlogger.auto

logging.basicConfig(level=logging.INFO)  
logger = logging.getLogger(__name__)

Result: Import error or unexpected behavior

❌ MISTAKE 3: Config Before Import

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

βœ… CORRECT WAY

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!

❓ FAQ

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.

πŸ“„ License

MIT License - see LICENSE file for details.

Feel free to use SmartLogger in your projects, both personal and commercial!

πŸ‘¨β€πŸ’» Author

Mohammad Rasol Esfandiari

Mohammad Rasol Esfandiari

🐍 Python Developer & Open Source Enthusiast

GitHub Email


🌟 If SmartLogger made your logging beautiful, please give it a star!

GitHub stars

Made with ❀️ for the Python community

Transform your logs from boring to beautiful in seconds! 🎨

About

🎨 Beautiful, colorful logging for Python with zero configuration. Transform boring logs into colorful masterpieces instantly!

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages