Skip to content

FastAPI interface

Logfirewill FastAPI custom and third party tools with logfire.instrument_fastapi() methods.

install

Install logfire using fastapi extra:

{{ install_logfire(extras=['fastapi']) }}

usage

We have a minimal example below. Please install Uvicorn to run it:

pip install uvicorn

You can run it with python main.py:

main.py
import logfire
from fastapi import FastAPI

app = FastAPI()

logfire.configure()
logfire.instrument_fastapi(app)


@app.get("/hello")
async def hello(name: str):
    return {"message": f"hello {name}"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app)

Then visit http://localhost:8000/hello?name=world and check the logs.

OpenTelemetry FastAPI Stacking

The third-party OpenTelemetry FastAPI Instrumentation package adds a span to each request, which contains detailed attributes about the HTTP request, such as the full URL and user agent. With the start and end times, you can see how long it takes to process each request.

[logfire.instrument_fastapi()][logfire. By default, Logfire.instrument_fastapi] Apply this detection. You can disable it by passing use_opentelemetry_instrumentation=False.

logfire.instrument_fastapi() also takes arbitrary additional keyword arguments and passes them to the OpenTelemetry FastAPIInstrumentor.instrument_app() method. See its documentation for more details.

Logfire Storing: Logging endpoint parameters and validation errors

logfire.instrument_fastapi() will issue a span called FastAPI 参数 for each request, which shows how long FastAPI takes to parse and validate endpoint function parameters in the request and resolve any dependencies. By default, the span will also contain the following properties:

  • values: A dictionary that maps the parameter names of endpoint functions to parsed and validated values.

  • errors: List of validation errors for any invalid input.

You can customize this function by passing the request_attributes_mapper function to instrument_fastapi. This function will be called with Request or WebSocket objects and the default property dictionary. It should return a new property dictionary, or return None with the span level set to "debug" so that it is hidden by default. For example:

import logfire

app = ...


def request_attributes_mapper(request, attributes):
    if attributes["errors"]:
        # Only log validation errors, not valid arguments
        return {
            "errors": attributes["errors"],
            "my_custom_attribute": ...,
        }
    else:
        # Don't log anything for valid requests
        return None


logfire.configure()
logfire.instrument_fastapi(app, request_attributes_mapper=request_attributes_mapper)

Attention

The [request_attributes_mapper ][logfire.Logfire.instrument_fastapi(request_attributes_mapper)] function must not change the contents of 值 or 错误, but it can safely replace them with new values.

Excluding URLs from detection

To avoid tracking certain URLs, you can specify a comma-separated regular expression that will match the full request URL. This can be passed to:

  • instrument_fastapi such as [excluded_urls ][logfire.Logfire.instrument_fastapi(excluded_urls)], e.g.logfire.instrument_fastapi(app, excluded_urls='/health')

  • Environment variable OTEL_PYTHON_FASTAPI_EXCLUDED_URLS.

  • The environment variable OTEL_PYTHON_EXCLUDED_URLS(this also applies to other detections).

Capture request and response headers


本文总阅读量次