Skip to content
v1
Docs

Python SDK

WatchTower15 in Flask

Terminal window
pip install "watchtower15[flask]"
from flask import Flask
from watchtower15.integrations.flask import WatchTower15
app = Flask(__name__)
app.config["WATCHTOWER15_APP_INFO"] = "billing/2.4.1"
app.config["WATCHTOWER15_ALLOW_LIST"] = {"orders.created": "count"}
wt15 = WatchTower15(app) # or WatchTower15().init_app(app) in an application factory
@app.post("/orders")
def create_order():
app.extensions["watchtower15"].aggregator.increment("orders.created")
return "", 201

init_app reads the WATCHTOWER15_* keys of app.config: API_KEY, METRICS_TOKEN, LOGS_TOKEN, API_URL, INGEST_URL, APP_INFO, ALLOW_LIST, HEARTBEAT, ENABLED, FLUSH (background or per_request) and FAKE. A credential or URL left out is read from the matching WT15_* variable; keep credentials in the environment. It registers the extension in app.extensions["watchtower15"] and builds nothing until it is used.

  • .client is the shared sync Client, built at first use.
  • .aggregator is the shared aggregator, on a Client of its own that holds the metrics token alone, so a wrong API key never stops counting.
  • .close() closes the aggregator and drains the log handlers within 10 seconds, and closes the client: call it from your server’s shutdown if you have a hook (gunicorn’s worker_exit).
import logging
from watchtower15.integrations.logging import WatchTower15Handler
handler = WatchTower15Handler(lambda: app.extensions["watchtower15"].client, stream="billing")
app.logger.addHandler(handler)

A callable is asked for the client at each flush, so the handler shares the extension’s settings and never builds one at import.

With WATCHTOWER15_FLUSH = "per_request" the aggregator starts no thread, and a teardown_request hook sends the open minute’s metrics and drains the log handlers after every request, never raising. See servers, workers and serverless.

app.config["WATCHTOWER15_FAKE"] = True makes .client a FakeClient and .aggregator a FakeAggregator: nothing leaves the process and no credential is needed. See testing.