Spaces:
Runtime error
Runtime error
Download app/middleware/performance_middleware.py from junaidte14/aiverse: direct link, hf CLI and curl.
- Browser
- Download file 1.39 kB
-
https://huggingface.co/spaces/junaidte14/aiverse/resolve/main/app/middleware/performance_middleware.py
- Command line
-
hf download hf://spaces/junaidte14/aiverse/app/middleware/performance_middleware.py
-
curl -L -o performance_middleware.py https://huggingface.co/spaces/junaidte14/aiverse/resolve/main/app/middleware/performance_middleware.py
1.39 kB
| """ | |
| Performance monitoring middleware | |
| Tracks slow requests and performance metrics | |
| """ | |
| import time | |
| from fastapi import Request | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from app.utils.logger import logger | |
| class PerformanceMiddleware(BaseHTTPMiddleware): | |
| """ | |
| Monitor request performance | |
| Logs warnings for slow requests | |
| """ | |
| def __init__(self, app, slow_request_threshold: float = 1.0): | |
| """ | |
| Initialize performance middleware | |
| Args: | |
| app: ASGI application | |
| slow_request_threshold: Threshold in seconds for slow request warning | |
| """ | |
| super().__init__(app) | |
| self.slow_request_threshold = slow_request_threshold | |
| async def dispatch(self, request: Request, call_next): | |
| """Monitor request performance""" | |
| start_time = time.time() | |
| response = await call_next(request) | |
| duration = time.time() - start_time | |
| # Log slow requests | |
| if duration > self.slow_request_threshold: | |
| logger.warning( | |
| "Slow request detected", | |
| extra={ | |
| "method": request.method, | |
| "url": str(request.url), | |
| "duration_seconds": round(duration, 2), | |
| "threshold_seconds": self.slow_request_threshold, | |
| }, | |
| ) | |
| return response | |