# WatchTower15 in Celery

```sh
pip install "watchtower15[celery]"
```

```python
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](https://developer.watchtower15.com/sdks/python/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](https://developer.watchtower15.com/sdks/python/deployment/)), 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.

## Metrics from a task

```python
@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()`.

## Tests

Build the aggregator and the client from the [fakes](https://developer.watchtower15.com/sdks/python/testing/) (`FakeClient`, `FakeAggregator(client)`) and pass them to `install()`; nothing leaves the process.

Source: https://developer.watchtower15.com/sdks/python/celery/
