Concurrent Log Handler

0.9.29 · active · verified Fri Apr 10

A robust drop-in replacement for Python's `RotatingFileHandler` and `TimedRotatingFileHandler` that supports safe concurrent writes from multiple processes and threads. It also includes features like gzip compression and better Windows compatibility. The library is actively maintained, with frequent minor releases addressing bugs and adding features, typically every few months.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up a basic logger using `ConcurrentRotatingFileHandler` to ensure log file rotation works safely across multiple processes, preventing data loss or corruption due to concurrent writes. It configures a log file to rotate after reaching 10MB, keeping 5 backup copies.

import logging
import os
from concurrent_log_handler import ConcurrentRotatingFileHandler

log_file_path = os.path.join(os.getcwd(), 'app.log')

# Configure logging
log = logging.getLogger('my_app')
log.setLevel(logging.INFO)

# Use ConcurrentRotatingFileHandler
# Rotate log after reaching 10MB, keep 5 old copies.
# Set encoding to 'utf-8' to avoid UnicodeEncodeError on some systems.
handler = ConcurrentRotatingFileHandler(
    log_file_path, 'a', 10 * 1024 * 1024, 5, encoding='utf-8'
)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)

log.info('This is an informational message.')
log.warning('This is a warning message.')
log.error('This is an error message.')

print(f"Log messages written to: {log_file_path}")

view raw JSON →