File size: 1,037 Bytes
9796e1e
 
 
 
 
 
 
 
e406ddb
9796e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import time
from starlette.middleware.base import BaseHTTPMiddleware
from app.db import crud
from fastapi import Request


class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # Ignore les routes non enregistrées (ex: /docs, /openapi.json)
        if request.url.path not in request.app.state.logged_paths:
            return await call_next(request)
        start = time.time()
        response = await call_next(request)
        response_time_ms = (time.time() - start) * 1000
        prediction_id = getattr(request.state, "prediction_id", None)
        db = request.app.state.SessionLocal()
        try:
            crud.log_request(
                db=db,
                endpoint=request.url.path,
                method=request.method,
                status_code=response.status_code,
                response_time_ms=round(response_time_ms, 2),
                prediction_id=prediction_id,
            )
        finally:
            db.close()
        return response