Skip to main content

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

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! ๐ŸŽจ

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

pysmartlogger-1.3.0.tar.gz (25.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pysmartlogger-1.3.0-py3-none-any.whl (14.5 kB view details)

Uploaded Python 3

File details

Details for the file pysmartlogger-1.3.0.tar.gz.

File metadata

  • Download URL: pysmartlogger-1.3.0.tar.gz
  • Upload date:
  • Size: 25.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.4

File hashes

Hashes for pysmartlogger-1.3.0.tar.gz
Algorithm Hash digest
SHA256 c50c1a03a89c6e2de7e6e43004481ab0545209036c5e8655b4f2135c372535b9
MD5 2c28a2caaebee07524f11373c168bb35
BLAKE2b-256 a8c6aede504006b77d645436ea534e19d68463f14a3508af425ff149d2a1a6a5

See more details on using hashes here.

File details

Details for the file pysmartlogger-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: pysmartlogger-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 14.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.4

File hashes

Hashes for pysmartlogger-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 33043a12bc47babb4adb1a2a86f24e4060f9d863b911edff3dca77690da0b525
MD5 12911c3cc5c6c87877803111236cf850
BLAKE2b-256 f24e843661d6f3cb08a77aaf21b00ec7cebf82efb66f27392bb7f210cec28b78

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page