A powerful logging utility that surpasses the standard library
Project description
LoggingUtil
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
- Use
sanitize_keysto automatically redact sensitive data - Enable compression for log files
- Use structured logging for better security analysis
- Implement rate limiting for error logs
- Set appropriate file permissions
License
MIT License - see LICENSE for details.
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 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f8639fe1a8eefc5e8f88876ecc4f70cc55dff168bf5ef94cfb2f0889226a46eb
|
|
| MD5 |
9e31e092708acf8c5dade9736b895169
|
|
| BLAKE2b-256 |
45373c4096fa27caa1c4aaa9f35c7393c4c2c76f6a98beb134cebdb71b244066
|
Provenance
The following attestation bundles were made for loggingutil-2.0.1.tar.gz:
Publisher:
python-publish.yml on mochathehuman/loggingutil
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
loggingutil-2.0.1.tar.gz -
Subject digest:
f8639fe1a8eefc5e8f88876ecc4f70cc55dff168bf5ef94cfb2f0889226a46eb - Sigstore transparency entry: 213735628
- Sigstore integration time:
-
Permalink:
mochathehuman/loggingutil@8a8ce99aaa2761b3154ebda78a145412d76772b7 -
Branch / Tag:
refs/tags/v2.0.1 - Owner: https://github.com/mochathehuman
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@8a8ce99aaa2761b3154ebda78a145412d76772b7 -
Trigger Event:
release
-
Statement type:
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ef2812187beaa42b1fba1464ac534840de4f31a24dafbb80410424755cb7a5da
|
|
| MD5 |
7448a0854efc7aa995797d6547a02625
|
|
| BLAKE2b-256 |
e96c0fc4a4216712ca9a18b077f94aa1d3f52c7335e9193206211bae4d6db499
|
Provenance
The following attestation bundles were made for loggingutil-2.0.1-py3-none-any.whl:
Publisher:
python-publish.yml on mochathehuman/loggingutil
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
loggingutil-2.0.1-py3-none-any.whl -
Subject digest:
ef2812187beaa42b1fba1464ac534840de4f31a24dafbb80410424755cb7a5da - Sigstore transparency entry: 213735629
- Sigstore integration time:
-
Permalink:
mochathehuman/loggingutil@8a8ce99aaa2761b3154ebda78a145412d76772b7 -
Branch / Tag:
refs/tags/v2.0.1 - Owner: https://github.com/mochathehuman
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@8a8ce99aaa2761b3154ebda78a145412d76772b7 -
Trigger Event:
release
-
Statement type: