Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Response body info.response.body is still empty #236

Closed
trallnag opened this issue Mar 18, 2023 · 0 comments · Fixed by #237
Closed

Response body info.response.body is still empty #236

trallnag opened this issue Mar 18, 2023 · 0 comments · Fixed by #237
Assignees

Comments

@trallnag
Copy link
Owner

trallnag commented Mar 18, 2023

Minimal script to reproduce:

from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator, metrics

app = FastAPI()


@app.get("/ping")
def get_ping():
    return "pong" * 10000000

def instrumentation(info: metrics.Info) -> None:
    print("Length of response body: " + str(len(info.response.body)))

Instrumentator().instrument(app).add(instrumentation)

Start with uvicorn main:app and do curl localhost:8000/ping | wc -c.

Observe output. The body size is shown as zero.


Maybe it only works if response is being streamed?

Here is example with data being streamed:

from fastapi import FastAPI, StreamingResponse
from prometheus_fastapi_instrumentator import Instrumentator, metrics

app = FastAPI()

CHUNK_SIZE = 1024 * 1024
some_file_path = 'large_file.tar'
app = FastAPI()

@app.get('/')
def main():
    def iterfile():
        with open(some_file_path, 'rb') as f:
            while chunk := f.read(CHUNK_SIZE):
                yield chunk

    headers = {'Content-Disposition': 'attachment; filename="large_file.tar"'}
    return StreamingResponse(iterfile(), headers=headers, media_type='application/x-tar')

def instrumentation(info: metrics.Info) -> None:
    print("Length of response body: " + str(len(info.response.body)))

Instrumentator().instrument(app).add(instrumentation)

Try again. Don't forget to create a largish file. 50 MB is fine. It now works.


Related #203 and #76.

@trallnag trallnag changed the title In custom instrumentation info.response.body is still empty Response body info.response.body is still empty Mar 18, 2023
@trallnag trallnag self-assigned this Mar 18, 2023
@trallnag trallnag linked a pull request Mar 19, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant