# Monitoring

Watch a self-hosted Cohorly: the health endpoint, the Prometheus metrics the API and the error worker expose and how to keep them private, JSON logs, and the optional Grafana Cloud profile.

## Health

`GET /health` is served through the proxy, needs no credential and answers:

```json
{ "ok": true, "db": true }
```

`db` is `false` when the API cannot reach PostgreSQL, and the response is
still HTTP 200. Point your uptime monitor at
`https://cohorly.example.com/health` and have it check the body for
`"db":true`, not only the status code: that checks the proxy, the API and the
database in one request.

Every service in the compose file, except the optional `alloy`, also has a
container health check. `docker compose ps` shows each as `healthy` or
`unhealthy`. The error
worker answers its own check on its metrics port, and reports unhealthy when
it has stopped taking work.

## Metrics

The API and the error worker each serve Prometheus metrics on port `9464`,
at `/metrics`. The port is `METRICS_PORT`, a separate listener from the API's
own port.

**The metrics port has no authentication and is private by design.** The
compose file does not publish it, and the proxy does not send `/metrics` to
the API, so it is reachable only from containers on the Compose network. Keep it that way:
do not add it to `ports`, and do not route it through Caddy.

To scrape it, run Prometheus (or an agent that speaks the Prometheus format) on
the Compose network. Add it as a service in `docker-compose.override.yml`, or
connect an existing container to the network with
`docker network connect <project>_default <container>`, where `<project>` is
the name of the directory that holds `docker-compose.yml`. Then:

```yaml
scrape_configs:
  - job_name: cohorly-api
    static_configs:
      - targets: ["server:9464"]
  - job_name: cohorly-error-worker
    static_configs:
      - targets: ["error-worker:9464"]
```

To read the endpoint by hand:

```bash
docker compose exec -T error-worker node -e \
  "fetch('http://server:9464/metrics').then(r => r.text()).then(console.log)"
```

What the metrics expose, besides the standard Node.js process metrics
(memory, CPU, event loop, garbage collection):

| Metric                                                                                                                                | Meaning                                                                                                        |
| ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `http_request_duration_seconds`                                                                                                       | API request duration, by method, route pattern and status code. Routes are patterns, never raw paths with ids. |
| `cohorly_events_ingested_total`                                                                                                       | Events received on `/track`, by result.                                                                        |
| `cohorly_events_imported_total`                                                                                                       | Events received by the historical import, by result.                                                           |
| `cohorly_rate_limit_rejections_total`                                                                                                 | Requests refused by a rate limiter, by which limiter.                                                          |
| `cohorly_query_timeouts_total`                                                                                                        | Analysis queries cancelled by `COHORLY_QUERY_TIMEOUT_MS`.                                                      |
| `cohorly_query_too_large_total`                                                                                                       | Analysis statements stopped by `COHORLY_QUERY_MAX_ROWS` (one query can count more than once).                  |
| `cohorly_exceptions_ingested_total`                                                                                                   | Exceptions received, by result.                                                                                |
| `cohorly_error_worker_payloads_total`, `cohorly_error_worker_batch_duration_seconds`                                                  | What the error worker processed, and how long a batch took.                                                    |
| `cohorly_exception_staging_oldest_age_seconds`                                                                                        | Age of the oldest exception waiting for the worker. A value that keeps growing means the worker is stuck.      |
| `cohorly_pg_pool_total_connections`, `cohorly_pg_pool_idle_connections`, `cohorly_pg_pool_waiting_requests`                           | State of the database connection pool. Waiting requests above zero for long mean the pool is too small.        |
| `cohorly_identity_links_total`, `cohorly_identity_link_duration_seconds`                                                              | Identity linking outcomes and duration.                                                                        |
| `cohorly_mcp_tool_calls_total`, `cohorly_mcp_tool_duration_seconds`, `cohorly_mcp_auth_failures_total`, `cohorly_mcp_approvals_total` | Use of the MCP server.                                                                                         |

Labels never carry organization, project, user or event names. The
`cohorly_ai_*` metrics have no data unless you turn on the AI chat agent.

A starting set of alerts: `/health` whose body does not have `"ok":true` and
`"db":true`, `cohorly_exception_staging_oldest_age_seconds`
growing, `cohorly_pg_pool_waiting_requests` above zero for minutes, a rising
rate of `http_request_duration_seconds` with `status_code="500"`, and disk use of
the Docker volume that holds `selfhost-pgdata`.

## Logs

The API and the worker write one JSON object per line to standard output. Each
line has a `level` (pino numbers: 30 info, 40 warn, 50 error), a `time`, a
`service` (`cohorly-api`) and the message. Each request writes a line with the
message `request`, the method, the route pattern, the path, the status, the
duration in milliseconds, the client IP address and user agent, and a
`request_id`. The API sends the same id back in the `x-request-id` response
header, so you can find the lines of one request. The IP address and user agent
are personal data under many regimes: keep that in mind for log retention.

```bash
docker compose logs -f server
docker compose logs --no-log-prefix server | jq -cR 'fromjson? | select(.level >= 40)'
docker compose logs --no-log-prefix server | jq -cR 'fromjson? | select(.msg == "request" and .status >= 500)'
```

`LOG_LEVEL` in `.env` sets the level (`info` by default).
`COHORLY_REQUEST_LOG_SAMPLE`, set through an override, is the fraction of
successful requests (0 to 1, default 1) that write a request line; responses
of 400 and above are always logged.

Docker keeps the logs of every service with the `json-file` driver, capped at
3 files of 10 MB per container, so the oldest lines are dropped. To keep them
longer, ship them from the Docker logs with the agent you already use.

Secrets are not logged. That includes the license key and the SMTP address.

## Optional Grafana Cloud profile

The compose file has an optional `monitoring` profile that runs Grafana Alloy:

```bash
docker compose --profile monitoring up -d
```

It sends host, container and application metrics and the container logs to a
Grafana Cloud stack, and needs the `GCLOUD_PROM_URL`, `GCLOUD_PROM_USER`,
`GCLOUD_LOKI_URL`, `GCLOUD_LOKI_USER` and `GCLOUD_RW_TOKEN` values in `.env`.
It also needs an Alloy configuration file at `monitoring/alloy/config.alloy`,
next to the directory with `docker-compose.yml`, which is not among the files
you download in [Install](/self-hosting/install). Ask your Cohorly contact for
it.

Think before you turn it on:

- **It leaves your network.** Metrics and logs go to Grafana Cloud.
- **It reads the Docker API and parts of the host.** Alloy does not mount the
  Docker socket: a small proxy (`docker-socket-proxy`) does, and passes on only
  the read requests Alloy makes (container list, inspect and logs). Inspecting
  a container shows its environment variables, so Alloy can read the other
  containers' settings, secrets included. It also mounts the host's `/proc` and
  `/sys` read-only, not the host's whole filesystem.
- **It ships the logs of every container on the host**, not only this stack's.

If you already run Prometheus or a log pipeline, scraping the metrics port as
described above does the same work with no data leaving your network.
