pydantic / logfire

Uncomplicated Observability for Python and beyond! 🪵🔥
https://docs.pydantic.dev/logfire/
MIT License
1.62k stars 46 forks source link

Does not automatically record FastAPI arguments of subapplications #188

Closed freddyaboulton closed 1 week ago

freddyaboulton commented 1 month ago

Description

What I see

If I define a post request in a FastAPI subapplication, it will not be recorded in the platform.

from fastapi import FastAPI
import secrets
import logfire
from pydantic import BaseModel
from typing import Any

class PredictBody(BaseModel):
    session_hash: str
    data: list[Any]

app = FastAPI()
subapp = FastAPI()

@subapp.post("/predict")
async def predict(body: PredictBody):
    return {"id": secrets.token_hex(16)}

app.mount("/api", subapp)

logfire.configure(pydantic_plugin=logfire.PydanticPlugin(record="all"))
logfire.instrument_fastapi(app)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, port=7860)

No FastAPI arguments are recorded in the POST trace

image

If I don't use a subapplication, the FastAPI arguments are recorded

from fastapi import FastAPI
import secrets
import logfire
from pydantic import BaseModel
from typing import Any

class PredictBody(BaseModel):
    session_hash: str
    data: list[Any]

app = FastAPI()

@app.post("/predict")
async def predict(body: PredictBody):
    return {"id": secrets.token_hex(16)}

logfire.configure(pydantic_plugin=logfire.PydanticPlugin(record="all"))
logfire.instrument_fastapi(app)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, port=7860)

What I would like to see

I would like the FastAPI arguments to be automatically recorded for my subapplications.

Python, Logfire & OS Versions, related packages (not required)

logfire="0.32.0"
platform="macOS-13.3.1-arm64-arm-64bit"
python="3.10.13 (main, Sep 11 2023, 08:16:02) [Clang 14.0.6 ]"
[related_packages]
requests="2.31.0"
pydantic="2.7.1"
fastapi="0.111.0"
protobuf="4.25.3"
rich="13.7.1"
tomli="2.0.1"
opentelemetry-api="1.24.0"
opentelemetry-exporter-otlp-proto-common="1.24.0"
opentelemetry-exporter-otlp-proto-http="1.24.0"
opentelemetry-instrumentation="0.45b0"
opentelemetry-instrumentation-asgi="0.45b0"
opentelemetry-instrumentation-fastapi="0.45b0"
opentelemetry-proto="1.24.0"
opentelemetry-sdk="1.24.0"
opentelemetry-semantic-conventions="0.45b0"
opentelemetry-util-http="0.45b0"
sneakyPad commented 2 weeks ago

Thanks for the well organized issue. I've gone through it and found that the problem is that the sub app is not registered within logfire. When you write the following:

logfire.instrument_fastapi(app)
logfire.instrument_fastapi(subapp)

The arguments will be logged along with the request. I think it's not ideal because it's a duplication in the code and the UI also shows it as a nested duplication (?), but a first step to mitigate your problem.

I'd like to take this and work on a solution. Can someone assign this to me?