Skip to content
v1
Docs

Python SDK

WatchTower15 in Celery

Terminal window
pip install "watchtower15[celery]"
from celery import Celery
from watchtower15 import Client
from watchtower15.integrations.celery import install
from watchtower15.integrations.logging import WatchTower15Handler
from watchtower15.metrics import Aggregator
app = Celery("billing", broker="…")
client = Client.from_environment()
metrics = Aggregator(client, allow_list={"jobs.done": "count"})
handler = WatchTower15Handler(client, stream="billing-worker")
install(app, aggregator=metrics, handler=handler) # flush="background" by default

install(app, aggregator=None, handler=None, flush="background") builds no client of its own: it flushes the aggregator and the handler you give it, and a None flushes nothing of that kind. In a Django project’s worker, pass Django’s aggregator() (Django). It connects the worker’s signals:

  • worker_process_init (each prefork child): renews the SDK’s locks, buffers and threads, which a fork would otherwise copy from the parent (why), and names celery/<version> in the User-Agent.
  • worker_process_shutdown and worker_shutdown: a final flush of the aggregator and the handler, each bounded by 10 seconds, never raising.
  • task_postrun, with flush="per_task": after each task, the aggregator’s final flush and the handler’s drain, for a worker that may be stopped without a shutdown signal. flush must be background or per_task.

install() returns an Installation; uninstall() disconnects every signal it connected.

@app.task
def build_invoice(order_id: int) -> None:
...
metrics.increment("jobs.done")

Each prefork child counts its own minute, and the points of every process count: custom metrics keep every sample, so nothing is shared between processes. The aggregator’s thread starts in the child at its first increment().

Build the aggregator and the client from the fakes (FakeClient, FakeAggregator(client)) and pass them to install(); nothing leaves the process.