I'm interested in getting the request body in a custom request formatter when using FastAPI. However, request.body() returns a coroutine and therefore requires the await keyword, but the _format_log_object method is not async. My custom formatter looks something like this:
class _RequestFormatter(json_logging.JSONRequestLogFormatter):
def _format_log_object(
self, record, request_util: json_logging.util.RequestUtil
):
request: Request = record.request_response_data._request
request_body_bytes = await request.body() # <--- can't do this!
request_body = bytes.decode(request_body_bytes)
log_obj = super()._format_log_object(record, request_util)
log_obj.update({"request_body": request_body})
return log_obj
Such an approach works in frameworks like Flask, where you don't have to use await to get the body, but fails for FastAPI. Do you have any suggestions on how to work around this?
I'm interested in getting the request body in a custom request formatter when using FastAPI. However,
request.body()returns a coroutine and therefore requires theawaitkeyword, but the_format_log_objectmethod is notasync. My custom formatter looks something like this:Such an approach works in frameworks like Flask, where you don't have to use
awaitto get the body, but fails for FastAPI. Do you have any suggestions on how to work around this?