# Custom metrics from PHP

You need a metric source token (`WT15_METRICS_TOKEN`, `wt15ms_…`): see [metric sources](https://docs.watchtower15.com/metrics/sources/) and the [ingest API](https://developer.watchtower15.com/ingest/metrics/) it wraps.

## Push points

```php
$result = $wt15->ingest->metrics->push([
    ['metric' => 'orders.completed', 'metric_type' => 'count', 'value' => 1],
    ['metric' => 'queue.depth', 'metric_type' => 'level', 'value' => 42, 'recorded_at' => new DateTimeImmutable()],
]);

$result->accepted;        // true when any chunk was accepted
$result->count;           // points stored
$result->rejected;        // every rejection reason, 0 where none
```

-   Every point that names a `metric` carries `metric_type`, `count` or `level`.
-   The SDK stamps no time. A point without `recorded_at` is stamped by the server on receipt.
-   `push()` cuts the points into chunks of at most 1,000 points and 1,000,000 bytes, keeps their order, gzips each, and sends one `Idempotency-Key` per chunk, built before the first attempt and reused by every retry, so a retry is never stored twice.
-   **Re-running an import.** A chunk holding a point older than 30 days gets a key derived from its content, so re-running the same import is stored once. For a recent import, pass your own key and keep it on the re-run: `push($points, idempotencyKey: 'import/orders-backfill')`. **Never reuse a key for other points**: metric ingest drops a repeat in silence (a key is kept 30 days per organisation).

List the metrics of the token’s source, their status and the cap:

```php
$listing = $wt15->ingest->metrics->list();
foreach ($listing->metrics as $metric) {
    echo $metric->key, ' ', $metric->type, ' ', $metric->status, "\n";
}
echo $listing->used, ' of ', $listing->maxMetrics, "\n";
```

## The aggregator

For counts and levels on the request path, without a request on the request path. `increment()` and `gauge()` write into a minute bucket in a store every process shares, in microseconds, and **never throw and never send**. A flush, once a minute, sends one request per closed bucket.

```php
use WatchTower15\Client;
use WatchTower15\Lifecycle\PhpShutdownStrategy;
use WatchTower15\Metrics\Aggregator;
use WatchTower15\Store\RedisStore;

$redis = new Redis();
$redis->connect('127.0.0.1');

$metrics = new Aggregator(
    client: Client::fromEnvironment(),
    store: new RedisStore($redis, prefix: 'myapp'),     // one prefix per application, no default
    allowList: ['orders.shipped' => 'count', 'queue.depth' => 'level'],
    heartbeat: 'myapp.flushes',
);
$metrics->registerShutdown(new PhpShutdownStrategy());  // or flush from cron, below

$metrics->increment('orders.shipped');
$metrics->gauge('queue.depth', 812);
```

-   A count is the sum of its bucket; a level is the last value written in it.
-   A bucket is closed 5 seconds after its minute ends. A flush sends the closed buckets, oldest first, within 10 requests and 90 seconds a run, with an `Idempotency-Key` frozen per bucket and chunk, so a resend after a timed-out success is stored once.
-   A refused token, a redirect, a transport error, a throttle or a 5xx keeps the bucket and stops the run; the next run resends it, for up to 60 minutes. Older buckets are dropped and counted.
-   **Nothing throws; failures are counted.** The next flush logs one warning, with counts and reasons only, never a value or a token.
-   **The heartbeat** adds 1 to a count key in every flush, so a stopped pipe shows as silence an alarm can see.
-   **The allow-list** keeps a typo from creating a billable metric: a key not in it, or used by the other method than its type, is dropped and counted.
-   The token can be a `Metrics\TokenProvider`, called only when something is about to be sent and kept for at most 300 seconds.

## Stores

| Store | Scope | Use it for |
| --- | --- | --- |
| `Store\RedisStore` | the fleet | PHP-FPM on several servers. A single Redis or Valkey primary; Redis Cluster is not supported. A prefix is required. |
| `Store\ApcuStore` | one host, one SAPI | One PHP-FPM server. APCu is not shared between PHP-FPM and the CLI, so a cron flush cannot use it. |
| `Store\FileStore` | one host | Bare PHP with neither: a directory the web user and the cron user can both write. Local filesystems only. |
| `Store\InMemoryStore` | one process | Long-running workers, CLI scripts and tests. |

## When to flush

| Runtime | Store | Flush |
| --- | --- | --- |
| PHP-FPM, several servers | `RedisStore` | cron `vendor/bin/watchtower15 flush` on one server, or `registerShutdown()` on all |
| PHP-FPM, one server | `RedisStore` or `FileStore` (cron), or `ApcuStore` (`registerShutdown()` only) | as above |
| Apache mod\_php | `RedisStore` or `FileStore` | cron: an after-response flush holds the response there |
| Long-running worker | `InMemoryStore` or a shared one | `flushIfDue()` in the loop; `registerShutdown()` for the final flush |
| CLI script, cron job | `InMemoryStore` | `registerShutdown()`, or `push()` |
| Serverless | none | `push()` at the end of the invocation |

```bash
# crontab: a bootstrap file that returns the Aggregator
* * * * * cd /app && vendor/bin/watchtower15 flush --bootstrap=config/wt15-metrics.php
```

The bootstrap path may also come from `WT15_METRICS_BOOTSTRAP`. `flush` exits 0 for a clean run, a disabled aggregator or another flush running, 1 for any other stop reason, and 2 when it cannot start. `--json` prints the report.

Under PHP-FPM a pool’s `request_terminate_timeout` must be above the flush’s worst case (40 s at the defaults), or flush from cron. Hosts that share a `RedisStore` need clocks within the 5-second grace (NTP).

Source: https://developer.watchtower15.com/sdks/php/metrics/
