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.1.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.1-py3-none-any.whl (13.9 kB view details)

Uploaded Python 3

File details

Details for the file log_interceptor-1.0.1.tar.gz.

File metadata

  • Download URL: log_interceptor-1.0.1.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.1.tar.gz
Algorithm Hash digest
SHA256 e1320f2e1e02c66c2e531a634cdeedabd30a698538df557897013bcd51894aad
MD5 ce6ff48a93e12e828dfc80334c3d0b88
BLAKE2b-256 cac85ce3ea632c8072a4ae56ca2646bcdeeed3e30ec5d958798191ecc3ac6fa7

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for log_interceptor-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c70427e00fdf0bc4e96ffa8da4624aa6dac7548b195a4f86ed0be798e1401f5b
MD5 dd6f85a3e4e671b09c104c849d472dbd
BLAKE2b-256 62018f29c24f2c75ca46e7986c7aeb480906649b7f1cb380d6319a8039906322

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