75 lines
2.1 KiB
Python
75 lines
2.1 KiB
Python
"""Log external API calls to the database and console."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from datetime import datetime, timezone
|
|
from typing import Optional
|
|
|
|
from app.database import SessionLocal
|
|
from app.models.external_api_log import ExternalApiLog
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def log_external_api_call(
|
|
direction: str,
|
|
target_type: str,
|
|
method: str,
|
|
path: str,
|
|
url_host: str,
|
|
duration_ms: int,
|
|
status_code: Optional[int] = None,
|
|
success: bool = True,
|
|
target_id: Optional[int] = None,
|
|
target_name: Optional[str] = None,
|
|
error_type: Optional[str] = None,
|
|
error_message: Optional[str] = None,
|
|
) -> None:
|
|
"""Persist an external API call log entry and write a structured console log.
|
|
|
|
No request/response bodies, tokens, cookies, or API keys are recorded.
|
|
"""
|
|
# Console log (structured, for Docker log aggregation)
|
|
logger.info(
|
|
"api_log direction=%s target_type=%s target_id=%s target_name=%s "
|
|
"method=%s path=%s url_host=%s status_code=%s success=%s "
|
|
"duration_ms=%d error_type=%s error_message=%s",
|
|
direction,
|
|
target_type,
|
|
target_id,
|
|
target_name or "",
|
|
method,
|
|
path,
|
|
url_host,
|
|
status_code or "",
|
|
success,
|
|
duration_ms,
|
|
error_type or "",
|
|
(error_message or "")[:200],
|
|
)
|
|
|
|
# DB persistence
|
|
db = SessionLocal()
|
|
try:
|
|
log = ExternalApiLog(
|
|
direction=direction,
|
|
target_type=target_type,
|
|
target_id=target_id,
|
|
target_name=target_name,
|
|
method=method,
|
|
path=path,
|
|
url_host=url_host,
|
|
status_code=status_code,
|
|
success=success,
|
|
duration_ms=duration_ms,
|
|
error_type=error_type,
|
|
error_message=error_message,
|
|
created_at=datetime.now(timezone.utc),
|
|
)
|
|
db.add(log)
|
|
db.commit()
|
|
except Exception:
|
|
logger.exception("failed to persist external API log entry")
|
|
finally:
|
|
db.close()
|