# Add OpenTelemetry Tracing to a Slim 4 App

Yes. An agent adds the OpenTelemetry PHP SDK to a Slim 4 app as a PSR-15 middleware with a span per route, proves it against a collector and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-opentelemetry/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 requests enter the app before it picks between manual and automatic instrumentation. In an app laid out like slimphp/Slim-Skeleton, `composer.json` requires `php ^7.4 || ^8.0`, `slim/slim ^4.12`, `slim/psr7 ^1.6`, `php-di/php-di ^6.4` and `monolog/monolog ^2.9`, with PHPUnit 9.6, PHPStan 1.10 and PHP_CodeSniffer for development. `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` and `app/routes.php`, then adds the routing, body parsing and error middleware itself before calling `$app->handle($request)`. `app/middleware.php` adds one middleware, `SessionMiddleware`; `app/dependencies.php` wires a Monolog `Logger` with a `UidProcessor` and a `StreamHandler` whose path and level come from `app/settings.php`, which also sets `displayErrorDetails` true. `app/routes.php` has an `OPTIONS` catch-all, `GET /`, and a `/users` group with `ListUsersAction` and `ViewUserAction` over an `InMemoryUserRepository`. `tests/TestCase.php` rebuilds the same container and app without the error middleware, and `.github/workflows/tests.yml` runs PHPUnit with Xdebug coverage on PHP 7.4, 8.0, 8.1 and 8.2, with `phpcs` and `phpstan` on 8.1 and a Coveralls upload.

The first decision is forced by versions, and the agent makes it explicit rather than quietly. The OpenTelemetry PHP SDK, `open-telemetry/sdk`, requires PHP 8.1, as do `open-telemetry/exporter-otlp` and the Monolog bridge; the zero-code route, `open-telemetry/opentelemetry-auto-slim`, also needs the `opentelemetry` extension installed with PECL. So tracing cannot land while `composer.json` promises 7.4 and 8.0. The pull request raises `php` to `^8.1`, drops 7.4 and 8.0 from the CI matrix, and chooses manual instrumentation through a middleware, so nothing in production needs a C extension and the same code runs on the `php:8-alpine` image `docker-compose.yml` already uses. The agent says in the description what the extension would add, Slim route spans and PDO or HTTP client spans with no code, and leaves it as a follow-up.

Then it writes the middleware. `src/Application/Middleware/TracingMiddleware.php` implements PSR-15, takes a `TracerInterface` from the container, and for each request starts a server span, sets the HTTP method, target, scheme and status attributes from the request and response, and names the span after the route pattern read through `RouteContext::fromRequest($request)->getRoute()`, which exists only after the routing middleware has run; the agent registers the new middleware in `app/middleware.php` so that, with Slim's last-in-first-out order and `addRoutingMiddleware()` called later in `index.php`, routing resolves before the span name is read, and it writes a test for the `/users/{id}` pattern to prove the order. An exception from the handler marks the span with the error status before `HttpErrorHandler` turns it into a response. `app/dependencies.php` gains a `TracerProviderInterface` built from `OTEL_SERVICE_NAME` and `OTEL_EXPORTER_OTLP_ENDPOINT`, with a `BatchSpanProcessor` over the OTLP HTTP exporter and a shutdown through the existing `ShutdownHandler` registration in `index.php`; the Monolog logger gets `open-telemetry/opentelemetry-logger-monolog`'s handler beside the `StreamHandler` so a log line carries the active trace id, and `settings.php` gets the two variables with empty defaults that turn tracing into a no-op exporter in development. The composer `allow-plugins` entry for `php-http/discovery` is set the way the SDK's install notes ask.

Then it proves spans leave the process. In its own sandbox the agent runs `composer install`, `vendor/bin/phpunit`, `vendor/bin/phpstan` and `vendor/bin/phpcs`, since `TestCase.php` builds the real container and the new dependency must resolve there too. It downloads the OpenTelemetry Collector binary, starts it with a receiver on the OTLP HTTP port and a `debug` exporter writing to a file, exports the two variables, serves the app with `php -S localhost:8080 -t public` as `composer start` does, requests `/`, `/users` and `/users/1`, and reads the collector's output for three server spans named by route pattern with `http.response.status_code` set, then requests `/users/99` to show a span with the error status from `UserNotFoundException`. The log file under `logs/` is read for the trace id beside the `UidProcessor` id on the same line.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add OpenTelemetry tracing to this Slim 4 app. Read composer.json, public/index.php, app/middleware.php, app/dependencies.php, app/settings.php, app/routes.php, tests/TestCase.php and the GitHub workflow first. Check the PHP version the OpenTelemetry SDK and OTLP exporter require against the composer constraint and the CI matrix, raise the constraint and trim the matrix only as far as needed, and say so. Use manual instrumentation through a PSR-15 middleware rather than the extension-based auto instrumentation, and explain the trade. Start a server span per request named after the Slim route pattern with the standard HTTP attributes, make sure routing has resolved before the name is read and write a test that proves it, mark spans with the error status on exceptions, wire a tracer provider with a batch processor and the OTLP HTTP exporter from OTEL_SERVICE_NAME and OTEL_EXPORTER_OTLP_ENDPOINT with a no-op default, and add the Monolog handler so log lines carry the trace id. Run phpunit, phpstan and phpcs. Download the OpenTelemetry Collector, run it with a debug exporter, serve the app, request the root, the users list, one user and a missing user, and quote the spans the collector printed. Open a pull request.",
  "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

A pull request that adds `TracingMiddleware.php` and its test, changes `composer.json` and `composer.lock`, `app/middleware.php`, `app/dependencies.php`, `app/settings.php` and `.github/workflows/tests.yml`, and touches no action or domain class. The description explains the PHP floor and the matrix change, shows the middleware beside the order it relies on, and quotes the collector's debug output: four server spans named `GET /`, `GET /users`, `GET /users/{id}` and `GET /users/{id}` with an error status, each with its HTTP attributes, plus one log line carrying a trace id.

The repository's `Tests` workflow runs on the pull request on the remaining PHP versions, with `phpcs` and `phpstan` on the analysis job, so a reviewer sees the suite and the static analysis pass with the SDK installed. Before merging, a reviewer decides whether to take the extension-based auto instrumentation as the next step, which the description costs out, and where the collector endpoint lives in each environment.

## Run it on every Linear issue labelled observability

A platform team files one issue per service that lacks tracing and labels it. In the console, an automation in the Project with the repository has a `linear` trigger on `linear.issue.labeled` with that label in `labels` and the prompt above, so labelling the issue starts a run that reads it after the prompt, does the work and opens a pull request linked to the issue; a `linear.issue.state_changed` trigger with the team's in-progress state mapped to `exec` in `states` does the same when the issue moves. The trigger fires only for changes made by a member of your Rush org, and the automation's `max_runs_per_hour` spaces out a batch of labelled issues.

From your own server the same request is a `POST /o/{org}/sessions` with the issue URL in `resources` beside the repository, and a `request_id` that is a UUID v5 of the issue id so a retried delivery starts nothing new. Each run reads its own `composer.json`, so a service already on PHP 8.2 skips the version change and a service with the `opentelemetry` extension in its image gets the auto instrumentation package instead of the middleware.

## Why run it on Rush?

Adding tracing to a PHP app is where version constraints and middleware order collide: the SDK's PHP floor is above what the skeleton promises, the span name depends on routing having run, and a batch processor that never flushes exports nothing while every test passes. The agent reads the real constraints, writes the order into a test, and runs a collector in its own sandbox to show the spans as they leave the process, so the pull request carries the collector's output instead of a claim that tracing is on.

Every command stays with the run, from `composer install` to the collector's debug lines, and the pull request quotes them. The same change across a team's PHP services costs no more attention than one, because each run reads that service's own constraints and opens its own pull request.

## Frequently asked questions

### Why does the pull request drop PHP 7.4 and 8.0?

Because `open-telemetry/sdk`, the OTLP exporter and the Monolog bridge require PHP 8.1, and Composer refuses to resolve them while `composer.json` promises older versions. The agent raises the constraint to `^8.1` and removes the two matrix entries, and the description says so in the first paragraph rather than burying it in the diff.

### Why a middleware instead of the automatic instrumentation?

The automatic package for Slim needs the `opentelemetry` PECL extension in every image that runs the app, and the skeleton's `docker-compose.yml` uses plain `php:8-alpine`. A PSR-15 middleware gives one server span per route with no extension, and the description lists what the extension would add on top.

### How is the span named after the route?

The middleware reads `RouteContext::fromRequest($request)->getRoute()` and uses the route's pattern, so `/users/1` and `/users/2` share the name `GET /users/{id}`. That works only after Slim's routing middleware has run, and the pull request includes a test that fails if the middleware order is changed.

### What happens when the collector is down?

The batch processor drops the spans it cannot export and the request still completes, which the agent checks by stopping the collector and requesting `/users` once more. With the endpoint variable unset the provider is a no-op, so development and the test suite export nothing.

### Do the logs change?

Each log line keeps the `UidProcessor` id and the `StreamHandler` path from `settings.php`, and gains the active trace id through the OpenTelemetry Monolog handler. The pull request quotes one line from `logs/app.log` beside the span it belongs to.

## More Slim jobs

- [Add Pagination to a Slim 4 List Endpoint](https://getrush.ai/run/add-pagination/slim/)
- [Add Prometheus Metrics to a Slim 4 App](https://getrush.ai/run/add-prometheus-metrics/slim/)
- [Add Rate Limiting to a Slim 4 App](https://getrush.ai/run/add-rate-limiting/slim/)

## The same job on other stacks

- [Add OpenTelemetry Tracing to a Temporal TypeScript Worker](https://getrush.ai/run/add-opentelemetry/temporal/)
- [Add OpenTelemetry Tracing to an Actix Web App](https://getrush.ai/run/add-opentelemetry/actix/)
- [Add OpenTelemetry Tracing to an aiohttp App](https://getrush.ai/run/add-opentelemetry/aiohttp/)

## 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/)
