A production-grade logging solution for Python applications featuring domain isolation, async/sync support, and comprehensive configuration.
- 🏷️ Domain-based logging - Isolate logs by application components (api, core, business, etc.)
- ⚡ Dual-mode operation - Switch between synchronous and asynchronous logging
- 📝 Multiple output formats - Plain text and structured JSON logging
- 📊 Multiple destinations - Console, file (with rotation), and custom handlers
- 🔧 Environment-configurable - All settings via environment variables or Pydantic model
- 🧵 Thread-safe - Designed for concurrent applications
- 🧹 Proper resource cleanup - Automatic handler termination on shutdown
- Python 3.11+
- Pydantic 2.0+
git clone git@github.com:a-ulianov/logging-manage-module.git
cd logging-manage-module
python -m venv venv
source venv/bin/activate # for Linux
# venv/Script/activate.bat # for Windows
pip install -r ./requrements.txtOr add to your project's dependencies.
from src import LoggerManager, LoggingSettings
# Initialize for API domain
api_manager = LoggerManager('api')
api_manager.configure(
LoggingSettings(
JSON=True,
LEVEL='DEBUG',
USE_ASYNC=True,
DIR='logs',
FILE='api.log'
)
)
# Get loggers
root_logger = api_manager.get_logger() # 'api'
auth_logger = api_manager.get_logger('v1.auth') # 'api.v1.auth'
# Log messages
auth_logger.info("Authentication request", extra={"context": {"user": "test"}})
# Cleanup (important!)
api_manager.shutdown()| Parameter | Type | Default | Description |
|---|---|---|---|
NAME |
str | '' |
Root logger name |
LEVEL |
str | 'INFO' |
Minimum log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
JSON |
bool | False |
Enable JSON formatting |
FORMAT |
str | '%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
Text format string |
USE_ASYNC |
bool | True |
Enable non-blocking async logging |
MAX_QUEUE_SIZE |
int | 1000 |
Max queue size for async mode |
DIR |
Optional[str] | 'logs' |
Log directory path |
FILE |
Optional[str] | 'app.log' |
Log filename |
MAX_BYTES |
int | 10MB |
Max log file size before rotation |
BACKUP_FILES_COUNT |
int | 5 |
Number of backup logs to keep |
All parameters can be set via environment variables with LOG_ prefix:
export LOG_LEVEL=DEBUG
export LOG_JSON=true
export LOG_USE_ASYNC=false# Separate domains for different components
from src import LoggerManager, LoggingSettings
api_manager = LoggerManager('api')
core_manager = LoggerManager('core')
api_manager.configure(LoggingSettings(JSON=True))
core_manager.configure(LoggingSettings(FORMAT='%(levelname)s - %(message)s'))
# Loggers maintain separate configurations
api_logger = api_manager.get_logger('v1')
core_logger = core_manager.get_logger('db')from src import LoggerManager, LoggingSettings
from logging.handlers import SysLogHandler
def create_custom_handlers():
handlers = []
syslog = SysLogHandler(address=('logs.example.com', 514))
handlers.append(syslog)
return handlers
manager = LoggerManager('custom')
settings = LoggingSettings()
manager.configure(settings, custom_handler_factory=create_custom_handlers)- Always call shutdown() - Failing to shutdown may lose queued log messages
- Use domain isolation - Prevents configuration conflicts between components
- Consider async for performance - Especially in I/O-bound applications
- Use JSON for production - Enables better log processing and analysis
- Monitor queue size - In async mode, set appropriate MAX_QUEUE_SIZE
❌ Premature shutdown
→ Ensure all logging operations complete before shutdown()
❌ Mixing sync/async modes
→ Stick to one mode per domain for consistency
❌ Unbounded queue growth
→ Set MAX_QUEUE_SIZE appropriate for your workload
❌ Overlapping domains
→ Use clear hierarchical naming (api.v1, api.v2)
Run tests with:
pytest -vKey test cases:
- Environment variable loading
- Domain isolation
- Async/sync mode switching
- Resource cleanup
- Handler configuration
logging-manage-module/
├── src # Source code package
│ ├── __init__.py # Public interface
│ └── logging # Module source code
│ ├── __init__.py # Public interface
│ ├── config.py # Configuration model
│ ├── factory.py # Pipeline construction
│ ├── manager.py # Domain lifecycle management
│ ├── handlers/ # Handler implementations
│ │ ├── __init__.py # Public interface
│ │ ├── base.py # Core handler factory
│ │ └── custom.py # Example custom handlers
│ └── formatters/ # Formatter implementations
│ ├── __init__.py # Public interface
│ ├── base.py # Core formatter factory
│ └── json.py # JSON formatter
├── tests/ # Comprehensive test suite
│ ├── __init__.py # Package file
│ └── test_logging.py # Unit tests
├── .gitignore
├── pyproject.toml # Project config and settings
├── readme.md # Documentation
└── requirements.txt # Dependencies
- Async mode adds ~5-10% overhead but prevents I/O blocking
- JSON formatting is ~15% slower than text but more machine-readable
- File rotation has minimal impact when properly sized
- Queue size should be 2-3x your peak message rate
MIT License - See LICENSE for details.
- Fork the repository
- Create your feature branch
- Add tests for your changes
- Submit a pull request
This module was designed for production use in high-load environments and has been battle-tested in several large-scale applications.