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/your-username/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.1.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.1.0-py3-none-any.whl (10.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: custom_logger_pkg-0.1.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.1.0.tar.gz
Algorithm Hash digest
SHA256 300fae42203d10c8cff10fa7212dc7280a087085e71638310e7501dea1757afa
MD5 3f2daa57a4561879d589d61f768fa95a
BLAKE2b-256 b34e177023964d462ae648abcf304566ee84d85afeff3410c6476fea6aaee2ba

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for custom_logger_pkg-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f837cda16d95056e786d31b035a15c12f707751dad6655f74948eb4ba8a9c6ea
MD5 491d1c099bf245c1c015fcd1622d23f3
BLAKE2b-256 7df2839142347a5c96977383e7c74ef887e43a1b6abc98773c7974d872d38c48

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