Skip to main content

A powerful logging utility that surpasses the standard library

Project description

LoggingUtil

PyPI version Tests Python Versions License Downloads Code style: black Documentation

pip install loggingutil

A powerful Python logging utility that combines simplicity with advanced features. Perfect for both simple scripts and enterprise applications.

Quick Start

from loggingutil import LogFile

# Simple usage
logger = LogFile("app.log")
logger.log("Hello, World!")

# With context and structured data
with logger.context(user_id="123"):
    logger.structured(
        event="user_login",
        ip="1.2.3.4",
        status="success"
    )

Features

  • Simple Interface - Easy to use, hard to misuse
  • Smart Rotation - By size, time, or custom rules
  • Structured Logging - JSON format with schema validation
  • Multiple Outputs - Console, File, Database, Cloud
  • Context Management - Track request flow
  • Smart Filtering - Rate limiting, sampling, deduplication
  • Async Support - High-performance logging
  • Data Safety - Automatic sensitive data redaction
  • Metrics - Built-in logging statistics
  • Extensible - Custom handlers and filters

Installation

pip install loggingutil

# With all extras (elasticsearch, cloudwatch, etc)
pip install loggingutil[all]

Common Use Cases

Basic Logging

from loggingutil import LogFile, LogLevel

logger = LogFile("app.log")

# Simple logging
logger.log("System started")

# With level and tag
logger.log("Invalid input", level=LogLevel.ERROR, tag="VALIDATION")

# Structured data
logger.structured(
    event="order_created",
    order_id="123",
    amount=99.99
)

Request Tracking

with logger.context(request_id="req-123", user="john"):
    with logger.correlation("txn-456"):
        logger.log("Processing payment")
        try:
            process_payment()
        except Exception as e:
            logger.log_exception(e)

Multiple Outputs

from loggingutil.handlers import ConsoleHandler, ElasticsearchHandler

logger = LogFile("app.log")

# Colored console output
logger.add_handler(ConsoleHandler(color=True))

# Elasticsearch for search
logger.add_handler(ElasticsearchHandler(
    "http://elasticsearch:9200",
    index_prefix="myapp"
))

Smart Filtering

from loggingutil.filters import RateLimitFilter, DuplicateFilter

# Limit error rates
logger.add_filter(RateLimitFilter(
    max_count=100,  # max 100 logs
    time_window=60,  # per minute
    group_by="error_type"  # per error type
))

# Prevent duplicate errors
logger.add_filter(DuplicateFilter(
    time_window=300,  # 5 minutes
    fields=["error_type", "user_id"]
))

Configuration

# From YAML
from loggingutil import LogConfig
config = LogConfig.from_yaml("logging.yaml")
logger = LogFile(**config)

# From environment
# LOGGINGUTIL_FILENAME=app.log
# LOGGINGUTIL_MODE=json
logger = LogFile()  # auto-loads from env

Cloud Integration

from loggingutil.handlers import CloudWatchHandler

logger.add_handler(CloudWatchHandler(
    log_group="myapp",
    log_stream="prod"
))

Advanced Configuration

logger = LogFile(
    # Basic settings
    filename="app.log",
    mode="json",  # or "text"
    level=LogLevel.INFO,
    
    # Rotation settings
    rotate_time="daily",  # or "hourly", None
    max_size_mb=100,
    keep_days=30,
    compress=True,
    
    # Performance settings
    batch_size=100,
    sampling_rate=0.1,  # sample 10% of logs
    
    # Security settings
    sanitize_keys=["password", "token", "key"],
    
    # Time settings
    use_utc=True,
    timestamp_format="[%Y-%m-%d %H:%M:%S.%f]"
)

Migration from stdlib logging

import logging
from loggingutil.adapter import LoggingUtilHandler

# Create LoggingUtil logger
logutil = LogFile("app.log")

# Create handler
handler = LoggingUtilHandler(logutil)

# Add to existing logger
logger = logging.getLogger("myapp")
logger.addHandler(handler)

# Use standard logging - it will use LoggingUtil
logger.info("Hello world", extra={"user_id": "123"})

Metrics and Monitoring

# Get logging statistics
stats = logger.get_metrics()
print(f"Error rate: {stats['log_counts']['ERROR']}/minute")
print(f"Uptime: {stats['uptime']}")

Custom Formatting

def my_formatter(log_entry: dict) -> str:
    return f"[CUSTOM] {log_entry['data']}\n"

logger = LogFile(custom_formatter=my_formatter)

Security Best Practices

  1. Use sanitize_keys to automatically redact sensitive data
  2. Enable compression for log files
  3. Use structured logging for better security analysis
  4. Implement rate limiting for error logs
  5. Set appropriate file permissions

License

MIT License - see LICENSE for details.

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

loggingutil-2.0.1.tar.gz (26.2 kB view details)

Uploaded Source

Built Distribution

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

loggingutil-2.0.1-py3-none-any.whl (20.3 kB view details)

Uploaded Python 3

File details

Details for the file loggingutil-2.0.1.tar.gz.

File metadata

  • Download URL: loggingutil-2.0.1.tar.gz
  • Upload date:
  • Size: 26.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for loggingutil-2.0.1.tar.gz
Algorithm Hash digest
SHA256 f8639fe1a8eefc5e8f88876ecc4f70cc55dff168bf5ef94cfb2f0889226a46eb
MD5 9e31e092708acf8c5dade9736b895169
BLAKE2b-256 45373c4096fa27caa1c4aaa9f35c7393c4c2c76f6a98beb134cebdb71b244066

See more details on using hashes here.

Provenance

The following attestation bundles were made for loggingutil-2.0.1.tar.gz:

Publisher: python-publish.yml on mochathehuman/loggingutil

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file loggingutil-2.0.1-py3-none-any.whl.

File metadata

  • Download URL: loggingutil-2.0.1-py3-none-any.whl
  • Upload date:
  • Size: 20.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for loggingutil-2.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ef2812187beaa42b1fba1464ac534840de4f31a24dafbb80410424755cb7a5da
MD5 7448a0854efc7aa995797d6547a02625
BLAKE2b-256 e96c0fc4a4216712ca9a18b077f94aa1d3f52c7335e9193206211bae4d6db499

See more details on using hashes here.

Provenance

The following attestation bundles were made for loggingutil-2.0.1-py3-none-any.whl:

Publisher: python-publish.yml on mochathehuman/loggingutil

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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