4/app/api/core/middleware/activity_tracker.py
2025-03-20 09:54:31 +01:00

52 lines
2.3 KiB
Python

Here's the `activity_tracker.py` file with the `ActivityTrackerMiddleware` class that logs request method, URL, and processing time:
```python
# app/api/core/middleware/activity_tracker.py
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)
try:
response = await call_next(request)
finally:
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 the entry point for the middleware, which is called for every incoming request.
Here's how the middleware works:
1. The `dispatch` method is called with the incoming `Request` object and a `call_next` function.
2. The current time is recorded using `time.time()` to calculate the processing time later.
3. The request method and URL are extracted from the `Request` object.
4. The `call_next` function is called with the `Request` object, which passes the request to the next middleware or the application itself. The response from the application is stored in the `response` variable.
5. After the response is received, the processing time is calculated by subtracting the start time from the current time.
6. A log message is constructed with the request method, URL, and processing time, and printed to the console using `print`.
7. The `response` is returned to the caller.
To use this middleware in your FastAPI application, you need to add it to the list of middleware in your `main.py` file:
```python
# main.py
from fastapi import FastAPI
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
app = FastAPI()
app.add_middleware(ActivityTrackerMiddleware)
# ... other routes and configurations ...
```
With this middleware in place, every incoming request to your FastAPI application will be logged with its method, URL, and processing time.