Universal structured logging with exact JSON schema for Python frameworks
Project description
json-logify
Universal structured logging with exact JSON schema for Python frameworks.
Features
- Exact JSON Schema: Consistent log format across all frameworks
- High Performance: Built with structlog and orjson for maximum speed
- Universal: Works with Django, FastAPI, Flask and standalone Python
- Security First: Automatic masking of sensitive data (passwords, tokens, etc.)
- Easy Setup: One-line configuration for most use cases
- Rich Context: Request IDs, user tracking, and custom payload support
- Smart Filtering: Configurable path ignoring and request/response body logging
- Modern Python: Full type hints and async support
Quick Start
Installation
# Basic installation
pip install json-logify
# For specific frameworks
pip install json-logify[django]
# pip install json-logify[fastapi] # Coming soon
# pip install json-logify[flask] # Coming soon
# Everything
pip install json-logify[all]
Basic Usage
from logify import info, error, debug, warning
# Basic logging with message
info("User logged in")
# With structured context
info("Payment processed", amount=100.0, currency="USD", user_id="user123")
# Different log levels
debug("Debug information", query_time=0.023)
warning("Slow database query detected", query_time=1.52, query_id="a1b2c3")
error("Payment failed", error_code="CARD_DECLINED", user_id="user123")
# Exception handling
try:
# Some code that might fail
result = some_function()
except Exception as e:
error("Operation failed", exception=str(e), operation="some_function")
Django Integration
1. Install with Django extras:
pip install json-logify[django]
2. Configure in settings.py:
from logify.django import get_logging_config
# Add middleware to MIDDLEWARE list
MIDDLEWARE = [
# ... other middleware
'logify.django.LogifyMiddleware', # ← Add this
]
# Configure logging with json-logify
LOGGING = get_logging_config(
service_name="my-django-app",
level="INFO",
max_string_length=200, # String truncation limit
sensitive_fields=[ # Fields to mask with "***"
"password", "passwd", "secret", "token", "api_key",
"access_token", "refresh_token", "session_key",
"credit_card", "cvv", "ssn", "authorization",
"cookie", "x-api-key", "custom_sensitive_field"
],
ignore_paths=[ # Paths to skip logging
"/health/", "/static/", "/favicon.ico",
"/admin/jsi18n/", "/metrics/"
]
)
# Optional: Reduce Django built-in logger noise
LOGGING['loggers'].update({
'django.utils.autoreload': {'level': 'WARNING'},
'django.db.backends': {'level': 'WARNING'},
'django.server': {'level': 'WARNING'},
'django.request': {'level': 'WARNING'},
})
3. Use in your views:
from logify import info, error, debug, warning
from django.http import JsonResponse
def process_payment(request):
# Log with automatic request context
info("Payment processing started",
user_id=request.user.id,
amount=request.POST.get('amount'))
try:
# Sensitive data gets automatically masked
info("User data received",
username=request.user.username, # ← Visible
password=request.POST.get('password'), # ← Masked: "***"
credit_card=request.POST.get('card'), # ← Masked: "***"
email=request.user.email) # ← Visible
# Your business logic
payment = process_payment_logic(request.POST)
# Log success
info("Payment completed",
payment_id=payment.id,
status="success",
amount=payment.amount)
return JsonResponse({"status": "success", "payment_id": payment.id})
except ValidationError as e:
error("Payment validation failed", error=e, user_id=request.user.id)
return JsonResponse({"status": "error", "message": str(e)}, status=400)
except Exception as e:
error("Payment processing failed", error=e)
return JsonResponse({"status": "error"}, status=500)
4. What you get automatically:
Request logging:
{
"timestamp": "2025-09-09T08:09:35.933Z",
"message": "Request started",
"level": "INFO",
"payload": {
"request_id": "b62e59b6-bae7-4a96-821d",
"service": "my-django-app",
"method": "POST",
"path": "/api/payment/",
"user_info": "User ID: 123: john_doe",
"headers": {
"Content-Type": "application/json",
"Authorization": "***", // ← Automatically masked
"User-Agent": "curl/8.7.1"
},
"request_body": {
"username": "john_doe",
"password": "***", // ← Automatically masked
"credit_card": "***" // ← Automatically masked
}
}
}
Your application logs:
{
"timestamp": "2025-09-09T08:09:35.934Z",
"message": "Payment completed",
"level": "INFO",
"payload": {
"request_id": "b62e59b6-bae7-4a96-821d", // ← Auto-linked to request
"payment_id": "pay_123456",
"status": "success",
"amount": 99.99
}
}
🔒 Security Features:
- Automatic masking: Passwords, tokens, API keys, credit cards →
"***" - Header filtering: Authorization, Cookie, X-API-Key →
"***" - Recursive masking: Works in nested objects and arrays
- Request/Response body: Limited size + content-type filtering
- Path ignoring: Skip health checks, static files, etc.
- Request and response bodies (with sensitive fields masked)
Advanced Usage
Context Management
from logify import bind, set_request_context, clear_request_context
# Bind context to a logger
logger = bind(service="auth", module="login")
logger.info("Processing login", user_id="123")
# Set request-level context (useful in middleware)
set_request_context(request_id="req-456", user_id="123")
info("User action", action="view_profile") # Includes request context
clear_request_context()
Performance Tracking
from logify import track_performance
@track_performance
def expensive_operation():
# Your code here
return "result"
# Automatically logs function start, completion, and duration
Custom Configuration
from logify import configure_logging
# Configure with custom settings
configure_logging(
service_name="myapp",
level="DEBUG"
)
Log Schema
All logs follow this exact JSON schema:
{
"timestamp": "2025-01-15T10:30:00.123Z",
"message": "Log message here",
"level": "INFO",
"error": "Error description (optional)",
"payload": {
"service": "myapp",
"request_id": "req-123",
"custom_field": "custom_value"
}
}
The error field is optional and will only appear when logging errors or exceptions.
Requirements
- Python 3.8+
- structlog >= 23.0.0
- orjson >= 3.8.0
License
MIT License - see LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
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
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 json_logify-0.1.3.tar.gz.
File metadata
- Download URL: json_logify-0.1.3.tar.gz
- Upload date:
- Size: 25.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
41577e9e64fcce0e39a6004c62988670bcb526a21b32e27e23248ab5735149ac
|
|
| MD5 |
52735c364ec007d4f33c65da9880fa0b
|
|
| BLAKE2b-256 |
ffcc3ed9e3db2ae448cf4c2c0d7eaab3adcf80249f751cc904aa0e565ad7ac14
|
File details
Details for the file json_logify-0.1.3-py3-none-any.whl.
File metadata
- Download URL: json_logify-0.1.3-py3-none-any.whl
- Upload date:
- Size: 16.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9f5e903d876770ef3cb46632f798075ba48daf95738a70188843c448470c628b
|
|
| MD5 |
2581f75eccd81524be7eabbfe6c81956
|
|
| BLAKE2b-256 |
86b135fb380444d373395757a7f8ae89fd605dadc6393468acfa17e86ad08710
|