Skip to main content

Python library for intercepting and monitoring changes in external log files in real-time

Project description

LogInterceptor

Tests Ruff Pyright codecov Python Version License: MIT

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:

๐Ÿ”ง 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:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Commit Rules

We use Conventional Commits:

  • feat: โ€” new functionality
  • fix: โ€” bug fix
  • docs: โ€” documentation changes
  • test: โ€” adding or changing tests
  • refactor: โ€” code refactoring
  • chore: โ€” 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

๐Ÿ—บ๏ธ 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

log_interceptor-1.0.0.tar.gz (27.0 kB view details)

Uploaded Source

Built Distribution

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

log_interceptor-1.0.0-py3-none-any.whl (13.9 kB view details)

Uploaded Python 3

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

Hashes for log_interceptor-1.0.0.tar.gz
Algorithm Hash digest
SHA256 f6c94977fc58a953c955f15a157d72805131d42f15bcd358804eec9e480ae382
MD5 92d617523a642f8ef5604734057edc3f
BLAKE2b-256 95f5a1b008544a25bc24417da7c4e29338344ef48447376b1db7bc3b7e494eaf

See more details on using hashes here.

File details

Details for the file log_interceptor-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for log_interceptor-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2d2dfd4f89432974431aac6ed6e9694588df5eb8b5a143a3e5300cf5036fdebd
MD5 e491b30fd374f968e908a6a6e9675393
BLAKE2b-256 3a7ba190cfe59cb5ad674c2db2d1f44bbb7a67740dce91da453b1cdb18727c90

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