I am trying to log all my FastAPI requests (who requested, what and what is the status code) by creating a custom APIRoute
-class. This is my custom Route-class:
class LoggingRoute(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = super().get_route_handler()
async def custom_route_handler(request: Request) -> Response:
response: Response = await original_route_handler(request)
log_request(
user = request.user,
url = request.url,
method = request.method,
status_code = response.status_code
)
return response
return custom_route_handler
The logging would work if we don't want to include request.user
to the logs. When trying to access the user, the following error is thrown:
AssertionError: AuthenticationMiddleware must be installed to access request.user
I guess the user-attribute of the request is not yet initialized inside the route handler. request.user
works well when handling the request later.
My question is: is there any way for me to get access to request.user
inside the custom_route_handler
-function? If not, is there another way to implement the logging functionality with ability to log the user as well?