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

# That's it! Just one import
import smartlogger.auto

No setup, no configuration files, no complex initialization. It just works!

๐Ÿ–ฅ๏ธ 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

# 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

  • โœ… 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 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

  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

โ“ 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

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.2.7.tar.gz (23.8 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.2.7-py3-none-any.whl (13.8 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pysmartlogger-1.2.7.tar.gz
Algorithm Hash digest
SHA256 7b356a383f67f21391f9cec0291a958c0e060979ab5e3466a4976b532ccb9c90
MD5 6e340651630690c515de5385e5b05211
BLAKE2b-256 7b45e88ed51369180fb9997f13eb5c09ace25d7f423bf2e4820e3a759c19a9ed

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pysmartlogger-1.2.7-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

Hashes for pysmartlogger-1.2.7-py3-none-any.whl
Algorithm Hash digest
SHA256 c42961cbd455b763e5daa5eb391b38396cc18600c5b3f7aaa1792efedb9dfbd6
MD5 13ed79d739b0b88c43d093237c00da69
BLAKE2b-256 01c602bdf76e8f5fcdb0750d45c6ba471150bbf064178c799342dffac1b2c59e

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