Skip to content
v1
Docs

Python SDK

WatchTower15 in FastAPI

Terminal window
pip install "watchtower15[fastapi]"
from fastapi import Depends, FastAPI
from watchtower15 import AsyncClient
from watchtower15.integrations.fastapi import WatchTower15
wt15 = WatchTower15(app_info="billing/2.4.1", allow_list={"orders.created": "count"})
app = FastAPI(lifespan=wt15.lifespan)
@app.get("/servers")
async def servers(client: AsyncClient = Depends(wt15.client)):
return [s.name async for s in client.servers.list(limit=50)]
@app.post("/orders")
def create_order():
wt15.aggregator.increment("orders.created")

WatchTower15(...) takes the credentials and URLs (each left out is read from the WT15_* variables), app_info, allow_list, heartbeat, enabled, flush (background or per_request) and fake. It builds nothing until it is used.

  • wt15.client is a dependency returning the shared AsyncClient, built at first use.
  • wt15.aggregator is the shared aggregator, on a sync Client of its own that holds the metrics token alone (the aggregator’s thread cannot use an AsyncClient). increment() only updates memory, so it is safe in an async def handler.
  • wt15.lifespan closes what was built when the app shuts down: the aggregator and the log handlers within 10 seconds, off the event loop, then the AsyncClient. If your app has a lifespan, wrap it: FastAPI(lifespan=wt15.lifespan_around(my_lifespan)); ours is entered first and left last.

Attach a WatchTower15Handler to the loggers you want shipped. With no client given it builds Client.from_environment() at its first flush:

import logging
from watchtower15.integrations.logging import WatchTower15Handler
logging.getLogger("billing").addHandler(WatchTower15Handler(stream="billing"))

With flush="per_request" the aggregator starts no thread, and the ASGI middleware flushes after each HTTP request, in a worker thread it waits for, so a Lambda invocation (with Mangum) ends after the flush:

wt15 = WatchTower15(flush="per_request", allow_list={"orders.created": "count"})
app.add_middleware(WatchTower15Middleware, wt15=wt15) # from watchtower15.integrations.fastapi

See servers, workers and serverless.

WatchTower15(fake=True) hands out an AsyncFakeClient and a FakeAggregator: nothing leaves the process and no credential is needed. See testing.