1

I am running fastAPI with the logging proposed here: How do I get my FastAPI application's console log in JSON format with a different structure and different fields?

And tried to add another log: response + request payload/body like this (in get_extra_info()):

response_body = b""
for chunk in response.body_iterator:
   response_body += chunk

But when running getting error:

--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.10/logging/__init__.py", line 1100, in emit
    msg = self.format(record)
  File "/usr/lib/python3.10/logging/__init__.py", line 943, in format
    return fmt.format(record)
  File "/home/mgarcarz/scripts/fastapi/./utils/app_logger_formatter.py", line 41, in format
    return json.dumps(get_access_log(record), indent=2)
  File "/home/mgarcarz/scripts/fastapi/./utils/app_logger_formatter.py", line 25, in get_access_log
    'req': record.extra_info['req'],
TypeError: 'coroutine' object is not subscriptable

When i tried this example: How to log raw HTTP request/response in Python FastAPI

Request body is logged correctly, but for response body i got error:

File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/responses.py", line 269, in wrap
    await func()
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/responses.py", line 263, in stream_response
    await send({"type": "http.response.body", "body": b"", "more_body": False})
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/middleware/errors.py", line 159, in _send
    await send(message)
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 561, in send
    raise RuntimeError("Response content shorter than Content-Length")
RuntimeError: Response content shorter than Content-Length

Any ideas how to get it fixed ?

Thanks,

user2913139
  • 557
  • 2
  • 5
  • 13
  • Hard to tell since you haven't provided enough information, but I suspect it's because you haven't awaited the response. Could you paste how you are accessing the response object? – theundeadmonk Dec 26 '22 at 19:46

0 Answers0