58 lines
1.8 KiB
Python
58 lines
1.8 KiB
Python
"""
|
|
Structured logging configuration for the Delphi Database FastAPI app.
|
|
|
|
This module configures structlog to output JSON logs and integrates
|
|
context variables so request-specific fields (e.g., request_id) are
|
|
included automatically in log records.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Any, Dict
|
|
|
|
import structlog
|
|
|
|
|
|
def _add_required_defaults(_: Any, __: str, event_dict: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""
|
|
Ensure all required fields exist on every log entry so downstream
|
|
consumers receive a consistent schema.
|
|
"""
|
|
# Required fields per project requirements
|
|
event_dict.setdefault("request_id", None)
|
|
event_dict.setdefault("http.method", None)
|
|
event_dict.setdefault("http.path", None)
|
|
event_dict.setdefault("status_code", None)
|
|
event_dict.setdefault("user.id", None)
|
|
event_dict.setdefault("duration_ms", None)
|
|
return event_dict
|
|
|
|
|
|
def setup_logging(log_level: int = logging.INFO) -> None:
|
|
"""
|
|
Configure structlog for JSON logging with contextvars support.
|
|
|
|
Args:
|
|
log_level: Minimum log level for application logs.
|
|
"""
|
|
# Configure stdlib logging basic config for third-party libs (uvicorn, etc.)
|
|
logging.basicConfig(level=log_level)
|
|
|
|
structlog.configure(
|
|
processors=[
|
|
structlog.contextvars.merge_contextvars,
|
|
structlog.stdlib.add_log_level,
|
|
_add_required_defaults,
|
|
structlog.processors.TimeStamper(fmt="iso", key="timestamp"),
|
|
structlog.processors.dict_tracebacks,
|
|
structlog.processors.JSONRenderer(),
|
|
],
|
|
context_class=dict,
|
|
logger_factory=structlog.stdlib.LoggerFactory(),
|
|
wrapper_class=structlog.make_filtering_bound_logger(log_level),
|
|
cache_logger_on_first_use=True,
|
|
)
|
|
|
|
|