Python SDK
WatchTower15 in Celery
pip install "watchtower15[celery]"from celery import Celeryfrom watchtower15 import Clientfrom watchtower15.integrations.celery import installfrom watchtower15.integrations.logging import WatchTower15Handlerfrom 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 defaultinstall(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 namescelery/<version>in theUser-Agent.worker_process_shutdownandworker_shutdown: a final flush of the aggregator and the handler, each bounded by 10 seconds, never raising.task_postrun, withflush="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.flushmust bebackgroundorper_task.
install() returns an Installation; uninstall() disconnects every signal it connected.
Metrics from a task
Section titled “Metrics from a task”@app.taskdef 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.