chore: add structured logging with structlog; add request_id middleware; replace std logging

This commit is contained in:
HotSwapp
2025-10-06 22:22:04 -05:00
parent b2d751f555
commit 0637fc2a63
8 changed files with 177 additions and 34 deletions

57
app/logging_config.py Normal file
View File

@@ -0,0 +1,57 @@
"""
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,
)