48 lines
1.5 KiB
Python
48 lines
1.5 KiB
Python
"""HTTP request logging middleware for debug mode."""
|
|
|
|
import logging
|
|
import time
|
|
from datetime import datetime, timezone
|
|
|
|
from fastapi import Request
|
|
from starlette.middleware.base import BaseHTTPMiddleware
|
|
from starlette.responses import Response
|
|
|
|
from app.core.database import async_session_maker
|
|
from app.models.log import LogEntry
|
|
from app.services.debug_service import DebugService
|
|
|
|
logger = logging.getLogger("voidea.http")
|
|
|
|
|
|
class DebugLoggingMiddleware(BaseHTTPMiddleware):
|
|
async def dispatch(self, request: Request, call_next):
|
|
start = time.time()
|
|
|
|
response: Response = await call_next(request)
|
|
|
|
elapsed_ms = int((time.time() - start) * 1000)
|
|
|
|
path = request.url.path
|
|
|
|
# Skip health check and static noise
|
|
if path in ("/health", "/api/v1/health") or path.startswith("/assets/") or path.startswith("/icons/") or path == "/":
|
|
return response
|
|
|
|
try:
|
|
async with async_session_maker() as db:
|
|
svc = DebugService(db)
|
|
if await svc.is_debug_mode():
|
|
log = LogEntry(
|
|
level="DEBUG",
|
|
source="http",
|
|
message=f"{request.method} {path} → {response.status_code} ({elapsed_ms}ms)",
|
|
details=None,
|
|
created_at=datetime.now(timezone.utc),
|
|
)
|
|
db.add(log)
|
|
await db.commit()
|
|
except Exception:
|
|
pass
|
|
|
|
return response |