# Add Prometheus Metrics to a Slim 4 App

Yes. An agent adds a request duration histogram and a counter labelled by route to a Slim 4 app, a /metrics endpoint, storage for php-fpm, tests, and a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-prometheus-metrics/slim/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the app is wired. In an app like slimphp/Slim-Skeleton, `public/index.php` builds a PHP-DI container from `app/settings.php`, `app/dependencies.php` and `app/repositories.php`, creates the app with `AppFactory`, registers `app/middleware.php`, then `app/routes.php`, and only afterwards calls `addRoutingMiddleware()`, `addBodyParsingMiddleware()` and `addErrorMiddleware()`. That order matters in Slim 4: the last middleware added runs first, so by the time anything in `app/middleware.php` runs, routing has already resolved the route. `app/middleware.php` adds only `SessionMiddleware`; `app/dependencies.php` defines a Monolog `LoggerInterface` from the `logger` settings; `app/routes.php` has `/`, `/users` and `/users/{id}`. `composer.json` allows PHP `^7.4 || ^8.0` with Slim `^4.12`, and `tests/TestCase.php` builds the same container and app in `getAppInstance()`, without the routing middleware. `.github/workflows/tests.yml` runs `phpcs`, `phpstan` (level 4 over `src`) and `phpunit` with coverage on PHP 7.4 through 8.2.

The agent adds `promphp/prometheus_client_php` with Composer. The current 2.15 releases require PHP 8.2, while 2.14 still accepts `^7.4|^8.0`, so it constrains the package to a release the whole CI matrix can install and says why in the pull request rather than quietly raising the PHP floor. A `metrics` block in `app/settings.php` chooses the storage, and `app/dependencies.php` builds a `CollectorRegistry` from it: `InMemory` for tests and for `php -S`, `APCng` for php-fpm where each worker is its own process and a shared store is the only way `/metrics` sees every request, and `Redis` for a multi-host deployment, with the class names and the APCu extension requirement written next to the setting.

The middleware is `src/Application/Middleware/MetricsMiddleware.php`. It records `hrtime(true)` before calling the handler, then observes `http_request_duration_seconds` (a histogram with buckets from a few milliseconds to ten seconds) and increments `http_requests_total`, both labelled with `method`, `route` and `status`. The `route` label is the pattern from `RouteContext::fromRequest($request)->getRoute()->getPattern()`, so `/users/{id}` is one series rather than one per user id, and `unmatched` when no route resolved. `app/routes.php` gets `GET /metrics`, handled by `src/Application/Actions/MetricsAction.php`, which renders `RenderTextFormat` with the content type the renderer exposes as `RenderTextFormat::MIME_TYPE`.

Tests follow `tests/Application/Actions/User/ListUserActionTest.php`: `tests/Application/Actions/MetricsActionTest.php` sets `InMemory` storage, performs `GET /users` and then `GET /metrics`, and asserts that the text contains the `http_requests_total` sample with `route` equal to `/users` and `status` equal to `200`. Because `getAppInstance()` never adds the routing middleware, the route attribute would be missing in tests, so the agent adds `$app->addRoutingMiddleware()` to the test harness to match `public/index.php`, and the pull request explains that one-line change. It installs PHP and Composer in its sandbox, runs `vendor/bin/phpcs` (PSR-12 from `phpcs.xml`), `vendor/bin/phpstan` and `vendor/bin/phpunit`, and starts `composer start` to scrape `/metrics` with `curl` once, before opening the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add Prometheus metrics to this Slim 4 app. Read composer.json, public/index.php, app/settings.php, app/dependencies.php, app/middleware.php, app/routes.php, src/Application/Actions/Action.php, src/Application/Middleware/SessionMiddleware.php, tests/TestCase.php, tests/Application/Actions/User/ListUserActionTest.php, phpunit.xml, phpstan.neon.dist, phpcs.xml and .github/workflows/tests.yml first. Require promphp/prometheus_client_php with a constraint every PHP version in the CI matrix can install and explain the choice. Add a metrics block to app/settings.php that selects InMemory, APCng or Redis storage, and define a CollectorRegistry in app/dependencies.php from it. Add src/Application/Middleware/MetricsMiddleware.php that observes an http_request_duration_seconds histogram and increments an http_requests_total counter, labelled by method, route pattern from RouteContext and status, with unmatched when no route resolved; register it in app/middleware.php. Add GET /metrics in app/routes.php served by src/Application/Actions/MetricsAction.php using RenderTextFormat and its MIME type. Add tests/Application/Actions/MetricsActionTest.php that requests /users then /metrics and asserts the counter sample for route /users with status 200, adding addRoutingMiddleware to tests/TestCase.php so the route pattern is available. Run vendor/bin/phpcs, vendor/bin/phpstan and vendor/bin/phpunit until they pass, scrape /metrics once with curl against composer start, then open a pull request that lists the metrics, their labels, and the storage to pick per deployment.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request changes `composer.json`, `composer.lock`, `app/settings.php`, `app/dependencies.php`, `app/middleware.php`, `app/routes.php` and `tests/TestCase.php`, and adds the middleware, the action and the test. Its description lists the two metrics with their labels and buckets, shows the first lines of a `/metrics` scrape from the sandbox, and quotes the phpcs, phpstan and phpunit output.

It explains the choices a reviewer will ask about: why the `route` label is the pattern and not the path (cardinality), why `InMemory` is wrong for php-fpm (each worker would report its own counts), and why the routing middleware had to be added to the test harness. It also says what is left out: `/metrics` is open on the app's port, and the description shows where to put a network rule or basic auth in front of it.

Before merging, a reviewer picks the storage for each environment, installs APCu where `APCng` is chosen, and decides whether the histogram buckets suit the app's typical latency.

## Run it on every PHP service without a scrape target

A platform team that runs several Slim services sends this body once per repository from its own server, each `POST /o/{org}/sessions` with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own bootstrap: a service that registers middleware before routing gets the pattern through a different hook, and one on Slim 3 gets the pull request explaining what differs.

An automation on the Project with a `linear` trigger on `linear.issue.labeled`, `observability` in `config.labels`, and the prompt 'this issue names a route or a job that needs its own metric; add it to the registry with labels that stay low-cardinality, extend the metrics test, and open a pull request' starts one run per labelled issue once the registry exists. The trigger adds the issue after the prompt and fills in nothing else.

## Why run it on Rush?

Metrics in a PHP app depend on how PHP runs: a counter that lives in one process is invisible to the next request under php-fpm, a `route` label built from the path explodes into one series per id, and a middleware registered on the wrong side of routing never sees the pattern. The agent reads the bootstrap order in `public/index.php`, picks storage per deployment and writes it down, and proves the label values in a test rather than in a description.

The scrape output, the test run and the diff stay with the run, so a reviewer sees the exact sample line a Prometheus server will read. A team with several services runs the same request across all of them at once.

## Frequently asked questions

### Why not InMemory storage in production?

Under php-fpm every worker is a separate process with its own memory, so each worker would answer `/metrics` with only the requests it handled. `APCng` uses the APCu shared cache across workers on one host; `Redis` works across hosts. `InMemory` is right for tests and for the built-in `php -S` server.

### Does /metrics need authentication?

It exposes route names and counts, which most teams do not publish. The pull request leaves it open on the app port and shows where to restrict it: a network rule on the scraper's address, or a small basic-auth middleware on that one route, matching how the rest of the app handles auth.

### Why label by route pattern and not by path?

A label value per path means a series per user id, which grows without bound and slows every query. The pattern `/users/{id}` is one series per route, which is what dashboards want. Requests that match no route are labelled `unmatched` so 404 traffic is still counted.

### Which PHP versions does this support?

The CI matrix runs 7.4 through 8.2, and the newest client releases need 8.2, so the agent constrains the package to a release that installs on all of them and says so. A project that has dropped 7.4 can lift the constraint in the same place.

## More Slim jobs

- [Add Rate Limiting to a Slim 4 App](https://getrush.ai/run/add-rate-limiting/slim/)
- [Add Request ID Logging to a Slim App](https://getrush.ai/run/add-request-id-logging/slim/)
- [Add HTTP Response Caching to a Slim 4 App](https://getrush.ai/run/add-response-caching/slim/)

## The same job on other stacks

- [Add Prometheus Metrics to a Socket.IO Server](https://getrush.ai/run/add-prometheus-metrics/socket-io/)
- [Expose Temporal Worker Metrics to Prometheus in a TypeScript Project](https://getrush.ai/run/add-prometheus-metrics/temporal/)
- [Add Prometheus Metrics to a Tokio Server](https://getrush.ai/run/add-prometheus-metrics/tokio/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
