Skip to content

FastAPI

LoglyMiddleware adds request_id, method, path, client, and user_agent to the Logly context for each request. It logs timing and exceptions automatically.

Installation

This integration requires the fastapi and starlette packages.

bash
uv add logly[fastapi]
bash
pip install "logly[fastapi]"
bash
uv add fastapi starlette
bash
pip install fastapi starlette

Missing Dependency

If fastapi or starlette is not installed, you'll see:

ModuleNotFoundError: No module named 'fastapi'

Usage

python
from fastapi import FastAPI
from logly.integrations.fastapi import LoglyMiddleware

app = FastAPI()
app.add_middleware(LoglyMiddleware)

Captured Fields

FieldSource
request_idUUID generated per request
methodHTTP method (GET, POST, etc.)
pathRequest path
clientClient IP address
user_agentUser-Agent header

Full Example

python
from fastapi import FastAPI
from logly import logger
from logly.integrations.fastapi import LoglyMiddleware

app = FastAPI()
app.add_middleware(LoglyMiddleware)

@app.get("/")
async def root():
    logger.info("Handling request")
    return {"message": "Hello World"}

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    logger.debug("Fetching item {}", item_id)
    return {"item_id": item_id}

Released under the MIT License.