Skip to content

Starlette

The logfire.instrument_starlette() method will create a span for every request to your Starlette application.

Installation

Install logfire with the starlette extra:

pip install 'logfire[starlette]'
uv add 'logfire[starlette]'
rye add logfire -E starlette
poetry add 'logfire[starlette]'

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 starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.requests import Request
from starlette.routing import Route

logfire.configure()


async def home(request: Request) -> PlainTextResponse:
    return PlainTextResponse("Hello, world!")


app = Starlette(routes=[Route("/", home)])
logfire.instrument_starlette(app)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app)

The keyword arguments of logfire.instrument_starlette() are passed to the StarletteInstrumentor.instrument_app() method of the OpenTelemetry Starlette Instrumentation package, read more about it here.

What about the OpenTelemetry ASGI middleware?

If you are a more experienced user, you might be wondering why we are not using the OpenTelemetry ASGI middleware. The reason is that the StarletteInstrumentor actually wraps the ASGI middleware and adds some additional information related to the routes.

Excluding URLs from instrumentation

Capturing request and response headers