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

26 lines
1.3 KiB
Python

import time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
import logging
logger = logging.getLogger(__name__)
class ActivityTrackerMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
logger.info(
f"Request: {request.method} {request.url.path} - Processing Time: {process_time:.6f} seconds"
)
return response
```
This code defines an `ActivityTrackerMiddleware` class that inherits from `BaseHTTPMiddleware` from the Starlette library. The `dispatch` method is overridden to log the request method, URL path, 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. For example:
```python
from fastapi import FastAPI
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
app = FastAPI()
app.add_middleware(ActivityTrackerMiddleware)
```
With this middleware in place, each incoming request will be logged with its method, URL path, and processing time.