Python SDK
WatchTower15 in FastAPI
pip install "watchtower15[fastapi]"from fastapi import Depends, FastAPIfrom watchtower15 import AsyncClientfrom 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.clientis a dependency returning the sharedAsyncClient, built at first use.wt15.aggregatoris the shared aggregator, on a syncClientof its own that holds the metrics token alone (the aggregator’s thread cannot use anAsyncClient).increment()only updates memory, so it is safe in anasync defhandler.wt15.lifespancloses what was built when the app shuts down: the aggregator and the log handlers within 10 seconds, off the event loop, then theAsyncClient. 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 loggingfrom watchtower15.integrations.logging import WatchTower15Handler
logging.getLogger("billing").addHandler(WatchTower15Handler(stream="billing"))Serverless: per-request flushing
Section titled “Serverless: per-request flushing”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.fastapiSee 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.