Python library for intercepting and monitoring changes in external log files in real-time
Project description
LogInterceptor
LogInterceptor is a Python library for intercepting and monitoring changes in external log files in real-time. Ideal for automated tests and application monitoring.
โจ Key Features
- ๐ Non-blocking execution โ uses separate threads for monitoring
- ๐ Flexible filtering โ support for regex, predicate functions, and composite filters
- ๐พ Memory buffering โ save logs with various overflow strategies
- ๐ฏ Callback system โ asynchronous handlers for new entries
- โธ๏ธ Pause/Resume โ control log capture without stopping monitoring
- ๐ Statistics โ track event count, uptime, and metrics
- ๐ท๏ธ Metadata โ timestamp and event_id for each line
- ๐ก๏ธ Reliability โ error handling, file rotation, recovery
- ๐ Cross-platform โ works on Linux and Windows
- ๐ Python 3.9+ โ full type hints support
- ๐งช Pytest integration โ ready-made fixtures for tests
๐ฆ Installation
pip install log-interceptor
For development:
git clone https://github.com/hash/log-interceptor.git
cd log-interceptor
pip install -e ".[dev]"
๐ Quick Start
Basic Usage
from log_interceptor import LogInterceptor
# Capture new lines written to file
with LogInterceptor(
source_file="app.log",
target_file="captured.log"
) as interceptor:
# Your code that generates logs
# New entries are automatically copied to captured.log
pass
Memory Buffering
from log_interceptor import LogInterceptor
interceptor = LogInterceptor(
source_file="app.log",
use_buffer=True,
buffer_size=1000
)
interceptor.start()
# Your code
# ...
# Get captured lines
lines = interceptor.get_buffered_lines()
print(lines)
interceptor.stop()
Log Filtering
from log_interceptor import LogInterceptor
from log_interceptor.filters import RegexFilter
# Capture only ERROR and CRITICAL
error_filter = RegexFilter(r"(ERROR|CRITICAL)", mode="whitelist")
with LogInterceptor(
source_file="app.log",
filters=[error_filter],
use_buffer=True
) as interceptor:
# Only lines with ERROR or CRITICAL will be captured
pass
Using Callbacks
from log_interceptor import LogInterceptor
def on_error_logged(line, timestamp, event_id):
if "ERROR" in line:
print(f"Error detected: {line}")
interceptor = LogInterceptor(source_file="app.log")
interceptor.add_callback(on_error_logged)
interceptor.start()
# Your code
interceptor.stop()
Pause/Resume for Flow Control
from log_interceptor import LogInterceptor
interceptor = LogInterceptor(source_file="app.log", use_buffer=True)
interceptor.start()
# Capture logs
# ...
# Pause capture for processing
interceptor.pause()
lines = interceptor.get_buffered_lines()
# Process lines...
interceptor.clear_buffer()
# Resume capture
interceptor.resume()
interceptor.stop()
Statistics and Metadata
from log_interceptor import LogInterceptor
with LogInterceptor(source_file="app.log", use_buffer=True) as interceptor:
# Your code
# ...
# Get statistics
stats = interceptor.get_stats()
print(f"Lines captured: {stats['lines_captured']}")
print(f"Uptime: {stats['uptime_seconds']:.2f}s")
# Get metadata
metadata = interceptor.get_lines_with_metadata()
for entry in metadata:
print(f"[{entry['event_id']}] {entry['line']}")
Pytest Integration
import pytest
from log_interceptor import LogInterceptor
@pytest.fixture
def log_interceptor(tmp_path):
"""Fixture for log interception in tests"""
log_file = tmp_path / "app.log"
log_file.touch()
interceptor = LogInterceptor(
source_file=log_file,
use_buffer=True
)
interceptor.start()
yield interceptor
interceptor.stop()
def test_application_logs_error(log_interceptor):
"""Verify that application logs errors"""
# Your code that should generate an ERROR log
run_application_that_logs_error()
# Check logs
lines = log_interceptor.get_buffered_lines()
assert any("ERROR" in line for line in lines)
๐ฏ Additional Features
Context Manager Support
with LogInterceptor(source_file="app.log", target_file="captured.log") as interceptor:
# Automatic start() on entry
# Your code
pass
# Automatic stop() on exit
Timestamp for Auditing
from log_interceptor import LogInterceptor
with LogInterceptor(
source_file="app.log",
target_file="captured.log",
add_timestamps=True # ISO 8601 format
) as interceptor:
# captured.log will contain:
# [CAPTURED_AT: 2025-11-27T14:30:45.123456+00:00] Log line
pass
Configuration and Presets
from log_interceptor import LogInterceptor, InterceptorConfig
# Using preset
config = InterceptorConfig.from_preset("aggressive")
# Or custom configuration
config = InterceptorConfig(
encoding="utf-8",
buffer_size=5000,
retry_max_attempts=5
)
interceptor = LogInterceptor(
source_file="app.log",
config=config
)
๐ Documentation
Full documentation is available in the docs/ directory:
- API Reference โ description of all classes and methods
- Technical Specifications โ detailed technical requirements
- Development Plan โ development plan using TDD methodology
๐ง Development
Environment Setup
# Clone repository
git clone https://github.com/hash/log-interceptor.git
cd log-interceptor
# Install development dependencies
pip install -e ".[dev]"
Running Tests
# All tests
pytest
# With coverage
pytest --cov=log_interceptor --cov-report=html
# Fast tests only
pytest -m "not slow"
Linting and Type Checking
# Check code
ruff check .
# Format
ruff format .
# Check types
pyright
๐๏ธ Architecture
log-interceptor/
โโโ log_interceptor/ # Main package
โ โโโ __init__.py # Public API
โ โโโ interceptor.py # LogInterceptor class
โ โโโ filters.py # Filter system
โ โโโ config.py # Configuration
โ โโโ exceptions.py # Exceptions
โโโ tests/ # Tests
โ โโโ conftest.py # Fixtures
โ โโโ mock_app.py # MockLogWriter for tests
โ โโโ test_interceptor.py # LogInterceptor tests
โ โโโ test_filters.py # Filter tests
โโโ docs/ # Documentation
๐ค Contributing
We welcome your contributions! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Commit Rules
We use Conventional Commits:
feat:โ new functionalityfix:โ bug fixdocs:โ documentation changestest:โ adding or changing testsrefactor:โ code refactoringchore:โ configuration changes, CI/CD
๐ Requirements
- Python 3.9+
- watchdog >= 3.0.0
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- watchdog โ for an excellent file system monitoring library
- All project contributors
๐ Contact
- GitHub Issues: https://github.com/hash/log-interceptor/issues
- Documentation: https://github.com/hash/log-interceptor
๐บ๏ธ Roadmap
- Basic file monitoring
- Filter system
- Memory buffering
- Callback system
- asyncio support
- Multiple file monitoring
- Structured logging support (JSON)
- Web UI for monitoring
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file log_interceptor-1.0.0.tar.gz.
File metadata
- Download URL: log_interceptor-1.0.0.tar.gz
- Upload date:
- Size: 27.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f6c94977fc58a953c955f15a157d72805131d42f15bcd358804eec9e480ae382
|
|
| MD5 |
92d617523a642f8ef5604734057edc3f
|
|
| BLAKE2b-256 |
95f5a1b008544a25bc24417da7c4e29338344ef48447376b1db7bc3b7e494eaf
|
File details
Details for the file log_interceptor-1.0.0-py3-none-any.whl.
File metadata
- Download URL: log_interceptor-1.0.0-py3-none-any.whl
- Upload date:
- Size: 13.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2d2dfd4f89432974431aac6ed6e9694588df5eb8b5a143a3e5300cf5036fdebd
|
|
| MD5 |
e491b30fd374f968e908a6a6e9675393
|
|
| BLAKE2b-256 |
3a7ba190cfe59cb5ad674c2db2d1f44bbb7a67740dce91da453b1cdb18727c90
|