2/app/api/core/middleware/activity_tracker.py
2025-03-20 12:08:13 +01:00

28 lines
1.5 KiB
Python

Here's the `activity_tracker.py` file with the `ActivityTrackerMiddleware` class that logs request method, URL, and processing time:
```python
import time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
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 = await call_next(request)
process_time = time.time() - start_time
log_message = f"{request_method} {request_url} - {process_time:.6f} seconds"
print(log_message)
return response
```
This middleware class extends the `BaseHTTPMiddleware` class from Starlette, which is the underlying ASGI server used by FastAPI. The `dispatch` method is overridden to handle the request and response lifecycle.
Here's what the code does:
To use this middleware in your FastAPI application, you need to add it to the list of middleware in your `main.py` file or wherever you create the FastAPI application instance:
```python
from fastapi import FastAPI
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
app = FastAPI()
app.add_middleware(ActivityTrackerMiddleware)
# Your application routes and other configurations
```
With this middleware in place, every incoming request to your FastAPI application will be logged with the request method, URL, and processing time.