Skip to main content

Professional Object-Oriented Logger for Python - Enhanced logging with SOLID principles

Project description

🎯 Custom Logger Package

PyPI version Python versions License: MIT

A Professional Object-Oriented Logger for Python - Enhanced logging with SOLID principles and best practices. Perfect for Django applications, web services, and any Python project requiring sophisticated logging capabilities.

🚀 Features

  • Object-Oriented Design: Built following SOLID principles and OOP best practices
  • Multiple Log Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL, SUCCESS
  • Colored Output: Beautiful colored console output with colorama
  • Caller Information: Automatically track file names, line numbers, classes, and methods
  • Configurable: Flexible configuration system for different environments
  • Extensible Architecture: Easy to extend with custom handlers and formatters
  • Singleton Pattern: Global logger instance with easy access
  • Type Safety: Enum-based log levels prevent string-based errors
  • Backward Compatible: Drop-in replacement for simple logging needs
  • Cross-Platform: Works on Windows, macOS, and Linux

📦 Installation

From PyPI (Recommended)

pip install custom-logger-pkg

From Source

git clone https://github.com/Saman-naruee/Custom-Logger.git
cd custom-logger
pip install -e .

🏗️ Architecture

The logger follows clean architecture principles:

  • LogLevel: Type-safe enumeration of log levels
  • LoggerConfig: Configuration management
  • LogFormatter: Message formatting logic
  • LogHandler: Abstract base for output handlers
  • ConsoleLogHandler: Console output implementation
  • CallerInfo: Caller information extraction
  • CustomLogger: Main logging class with singleton pattern

📖 Usage

Basic Usage

from custom_logger import info, debug, warning, error, success

# Simple logging
info("Application started successfully")
debug("This is a debug message")
warning("Something might be wrong")
error("Something went wrong!")
success("Operation completed successfully")

Advanced OOP Usage

from custom_logger import CustomLogger, LogLevel, LoggerConfig

# Get singleton instance
logger = CustomLogger.get_instance()

# Object-oriented logging
logger.info("System initialized")
logger.debug("Debug information")
logger.error("An error occurred")

# Direct enum usage
logger.log("Custom message", LogLevel.INFO)

# Custom configuration
config = LoggerConfig(
    show_caller=True,
    show_timestamp=True,
    color_output=True,
    level=LogLevel.DEBUG
)
logger = CustomLogger(config)
logger.debug("This message includes caller info")

Configuration Examples

from custom_logger import LoggerConfig, LogLevel

# Disable caller info, keep colors
config = LoggerConfig(
    show_caller=False,
    show_timestamp=True,
    color_output=True,
    level=LogLevel.INFO
)

# Development mode - show everything
dev_config = LoggerConfig(
    show_caller=True,
    show_timestamp=True,
    color_output=True,
    level=LogLevel.DEBUG
)

# Production mode - only important messages
prod_config = LoggerConfig(
    show_caller=False,
    show_timestamp=True,
    color_output=False,
    level=LogLevel.WARNING
)

Custom Handler Example

from custom_logger import LogHandler, LogLevel

class FileLogHandler(LogHandler):
    def __init__(self, filename):
        self.filename = filename
        self.file = open(filename, 'a')

    def handle(self, formatted_message: str, level: LogLevel) -> None:
        timestamp = datetime.now().isoformat()
        self.file.write(f"[{timestamp}] {formatted_message}\n")
        self.file.flush()

    def close(self):
        self.file.close()

🎨 Log Levels and Colors

Level Color Priority Usage
DEBUG Cyan 10 Detailed diagnostic information
INFO Green 20 General information messages
SUCCESS Bright Green 25 Success confirmation messages
WARNING Yellow 30 Warning messages
ERROR Red 40 Error messages
CRITICAL White on Red 50 Critical error messages

🧪 Testing

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run with coverage
coverage run -m pytest
coverage report -m

# Lint code
flake8 custom_logger/
black custom_logger/
mypy custom_logger/

🏭 Integration with Django

This logger works seamlessly with Django:

# In Django settings.py
from custom_logger import CustomLogger

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'custom_logger': {
            'class': 'logging.Handler',  # Custom handler implementation
        },
    },
}

# In Django views/models
from custom_logger import info, error

def my_view(request):
    info("User accessed the view")
    try:
        # Some logic
        success("Action completed successfully")
    except Exception as e:
        error(f"Error occurred: {e}")
        raise

📋 Requirements

  • Python >= 3.7
  • colorama >= 0.4.4

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🤝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Run the test suite
  6. Submit a pull request

🐛 Issues and Support

📚 More Examples

For more advanced examples and use cases, see the examples/ directory.

🎯 Best Practices

  1. Use appropriate log levels: Don't use ERROR for normal flow control
  2. Configure for environment: Different settings for development vs production
  3. Consider performance: DEBUG messages have minimal overhead but use sparingly in loops
  4. Structure your messages: Make them meaningful and searchable
  5. Use structured logging: Consider adding context and metadata

Enjoy professional logging with clean OOP design! 🚀

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

custom_logger_pkg-0.2.0.tar.gz (15.2 kB view details)

Uploaded Source

Built Distribution

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

custom_logger_pkg-0.2.0-py3-none-any.whl (10.7 kB view details)

Uploaded Python 3

File details

Details for the file custom_logger_pkg-0.2.0.tar.gz.

File metadata

  • Download URL: custom_logger_pkg-0.2.0.tar.gz
  • Upload date:
  • Size: 15.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for custom_logger_pkg-0.2.0.tar.gz
Algorithm Hash digest
SHA256 95bb66e0812aa5cc46b155329b6eb50af6b3dec7343580a87b77240252a83021
MD5 122a5e9b25de92ec7fb59f9385592126
BLAKE2b-256 aa25492a147559dc0549758ff5480cb6f0cc25cc0589775d2b0aa2c190c270bc

See more details on using hashes here.

File details

Details for the file custom_logger_pkg-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for custom_logger_pkg-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 84a545f9e50b8e3776314d4e74338348e1889ebb691c886f3bf408d80d17f805
MD5 5ca66c93b67252a82b62d774fc37f91c
BLAKE2b-256 329ef9fcd8209ae94329fbab02adb180706c5777325825750e718bea48b59a72

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