18 lines
1017 B
Python
18 lines
1017 B
Python
import time
|
|
from starlette.middleware.base import BaseHTTPMiddleware
|
|
from starlette.requests import Request
|
|
from starlette.responses import Response
|
|
from loguru import logger
|
|
class ActivityTrackerMiddleware(BaseHTTPMiddleware):
|
|
async def dispatch(self, request: Request, call_next):
|
|
start_time = time.time()
|
|
request_method = request.method
|
|
request_url = str(request.url)
|
|
response: Response = await call_next(request)
|
|
process_time = time.time() - start_time
|
|
logger.info(f"{request_method} {request_url} - Process Time: {process_time:.6f} seconds")
|
|
return response
|
|
```
|
|
This code defines an `ActivityTrackerMiddleware` class that inherits from `BaseHTTPMiddleware`. The `dispatch` method is overridden to log the request method, URL, and processing time for each incoming request.
|
|
Here's a breakdown of the code:
|
|
This middleware can be added to the FastAPI application by including it in the list of middleware instances when creating the application instance. |