chore: add structured logging with structlog; add request_id middleware; replace std logging
This commit is contained in:
57
app/logging_config.py
Normal file
57
app/logging_config.py
Normal 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,
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user