Structured JSON logging for Python applications, compatible with Serilog format.
pip install serilog-pythonimport logging
from serilog_python import setup_logging
# Basic setup
setup_logging()
logger = logging.getLogger(__name__)
logger.info("Application started", extra={"user_id": 123, "action": "login"})export APPLICATION_NAME="MyService"
export APPLICATION_VERSION="1.2.3"
export ENVIRONMENT="production"setup_logging(
level="DEBUG",
application_name="MyApp",
application_version="2.1.0",
environment="production",
exclude_fields=["password", "token"]
)from fastapi import FastAPI
from serilog_python import setup_logging
setup_logging(level="INFO", disable_access_logs=True)
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(user_id: int):
logger = logging.getLogger(__name__)
logger.info("Fetching user", extra={"user_id": user_id})
return {"user_id": user_id}# settings.py
from serilog_python import setup_logging
setup_logging(
application_name="MyDjangoApp",
environment="production"
)from flask import Flask
from serilog_python import setup_logging
setup_logging(application_name="MyFlaskApp")
app = Flask(__name__)Logs are output in JSON format:
{
"@timestamp": "2024-01-15T10:30:45.123Z",
"level": "Information",
"message": "User logged in",
"service": {
"name": "MyService",
"version": "1.2.3"
},
"environment": "production",
"user_id": 123,
"action": "login"
}Configure the entire logging system.
Parameters:
level(str): Logging level (default: "INFO")disable_access_logs(bool): Disable web server access logs (default: True)sql_level(str): SQL logging level (optional)application_name(str): Override application name (optional)application_version(str): Override application version (optional)environment(str): Override environment (optional)exclude_fields(list): Fields to exclude from logs (optional)
Filter that adds service and environment context to log records.
JSON formatter compatible with Serilog output format.
MIT License