# Add Structured Logging to a Slim 4 App

Yes. An agent switches your Slim 4 app's Monolog logger to JSON lines, logs one record per request, routes Slim's error log through it, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-structured-logging/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 logging is wired before changing its shape, because the skeleton logs from three places that do not share a logger. In an app started from slimphp/Slim-Skeleton, `composer.json` requires `monolog/monolog` ^2.9, `php-di/php-di` ^6.4 and `slim/slim` ^4.12, with PHPUnit, phpstan and phpcs for development. `app/settings.php` sets a `logger` block with the name `slim-app`, a path of `logs/app.log` or `php://stdout` when the `docker` environment variable is set, as `docker-compose.yml` does, and level debug; it also sets `displayErrorDetails` true and `logError` and `logErrorDetails` false. `app/dependencies.php` builds a Monolog `Logger` with a `UidProcessor` and a `StreamHandler`, so lines today are Monolog's default text format. The base `Action` class takes `LoggerInterface` in its constructor and `ListUsersAction` writes one info line, so actions already log through the container.

The third place is Slim's own error path, and it bypasses Monolog entirely. `public/index.php` constructs `HttpErrorHandler` with only the callable resolver and the response factory, and calls `addErrorMiddleware($displayErrorDetails, $logError, $logErrorDetails)` with no logger. Slim 4.12's `ErrorHandler` takes an optional `LoggerInterface` as a third constructor argument and falls back to its own `Slim\Logger`, which writes through PHP's `error_log`; `App::addErrorMiddleware` takes the same optional fourth argument. So with `logError` turned on, exceptions would go to the PHP error log in text while the application writes JSON to its own file. The agent passes `$container->get(LoggerInterface::class)` into both and sets `logError` and `logErrorDetails` true in `app/settings.php`, so a `500` produces a JSON record in the same stream as everything else.

The format change is in `app/dependencies.php`. The agent sets a `JsonFormatter` on the `StreamHandler`, adds `PsrLogMessageProcessor` so `{placeholders}` in messages are filled, and `WebProcessor`, which attaches the URL, client IP, method, server name and referrer from `$_SERVER` to every record's `extra`. The existing `UidProcessor` stays: its per-process uid lands in `extra.uid` on every record of one request, which is the correlation key a JSON log needs. A new `format` key in the `logger` settings, `json` or `line`, lets local development keep the readable format. A new `src/Application/Middleware/RequestLoggingMiddleware.php`, a PSR-15 middleware in the shape of the existing `SessionMiddleware`, logs one info record per request with `method`, `path`, `status` and `duration_ms` in its context, and `app/middleware.php` registers it. The error middleware is added last in `public/index.php` and so sits outermost, which means a `404` or `500` passes back through the new middleware and is logged with its status.

Tests follow the repository's own base class. `tests/Application/Middleware/RequestLoggingMiddlewareTest.php` extends `Tests\TestCase`, builds the app with `getAppInstance`, replaces `LoggerInterface` in the container with a Monolog logger holding a `TestHandler`, sends `GET /users` and a request to a route that does not exist, and asserts one record each with the right `path` and a `200` and a `404`. A second test points a `StreamHandler` at `php://memory` with the `JsonFormatter` and the processors, logs one record, and asserts the line decodes as JSON with `message`, `context`, `extra.uid` and `extra.http_method`. In the sandbox the agent runs `composer install`, `composer test`, `vendor/bin/phpstan` and `vendor/bin/phpcs` as `.github/workflows/tests.yml` does, starts `composer start`, sends `curl` to `/users` and `/users/9999`, shows the JSON lines in `logs/app.log`, and opens the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add structured logging 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/Actions/User/ListUsersAction.php, src/Application/Handlers/HttpErrorHandler.php, src/Application/Middleware/SessionMiddleware.php, tests/TestCase.php, phpunit.xml, docker-compose.yml and .github/workflows/tests.yml first. In app/dependencies.php set a Monolog JsonFormatter on the StreamHandler when a new logger.format setting is json, keep the UidProcessor, and add PsrLogMessageProcessor and WebProcessor. Add src/Application/Middleware/RequestLoggingMiddleware.php as a PSR-15 middleware that logs one info record per request with method, path, status and duration_ms in context, and register it in app/middleware.php. In app/settings.php set logError and logErrorDetails true and add format json. In public/index.php pass the container's LoggerInterface as the third argument of HttpErrorHandler and the fourth argument of addErrorMiddleware, and explain in the pull request that Slim otherwise logs errors through its own Slim\\Logger and PHP's error_log. Add tests/Application/Middleware/RequestLoggingMiddlewareTest.php extending Tests\\TestCase that swaps LoggerInterface for a Monolog logger with a TestHandler and asserts a record for GET /users with status 200 and for an unknown path with status 404, plus a test that a StreamHandler on php://memory with the JsonFormatter writes a line that decodes with message, context and extra.uid. Run composer install, composer test, vendor/bin/phpstan and vendor/bin/phpcs, start the app with composer start, curl /users and /users/9999, then open a pull request that pastes the test output and the JSON log lines.",
  "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

What comes back is a pull request that adds `src/Application/Middleware/RequestLoggingMiddleware.php` and `tests/Application/Middleware/RequestLoggingMiddlewareTest.php`, and changes `app/dependencies.php`, `app/settings.php`, `app/middleware.php` and `public/index.php`. The description pastes two lines from `logs/app.log`, the `200` for `/users` and the `404` for `/users/9999`, each a single JSON object with `message`, `context.status`, `context.duration_ms`, `extra.uid` and the `WebProcessor` fields, and a paragraph on why Slim's error handler now receives the Monolog logger.

The run's record holds `composer install`, the PHPUnit run with the existing action and domain tests plus the new cases, the phpstan and phpcs runs, the server start and the two requests. The actions, routes, repositories and the `HttpErrorHandler` class are untouched; the handler only gains a logger argument where it is constructed.

Before merging, a reviewer decides what `logErrorDetails` should be in production, since true writes stack traces into the JSON stream, whether `displayErrorDetails` should be turned off at the same time, and whether the log shipper the team uses wants one object per line, which `JsonFormatter` writes by default, or a different field layout.

## Run it on every new PHP service

A team with several Slim services starts one run per repository from its own server: one `POST /o/{org}/sessions` each, 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 rather than a second pull request. Each run reads that service's own `dependencies.php`, so a service that already uses a `RotatingFileHandler` keeps it and gains the formatter and processors, and a service with several loggers gets each one converted.

Afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds an error_log or var_dump call, or constructs a Monolog handler without the JsonFormatter, comment with the line and the logger to use instead" keeps the stream structured. The trigger adds the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

Switching a formatter is one line; the work is finding the log lines that never reach the formatter, and in this skeleton the error path is one of them because the error handler is built without the container's logger. The agent reads Slim's `ErrorHandler` and `App` at the pinned version to find the optional argument, wires it, and proves with a test that a `404` ends up in the same stream with the same fields as a `200`.

In its own sandbox the agent runs the tests, the static analysis and a real server, and the run keeps the JSON lines for the pull request. For a team with many PHP services, each gets its own run and its own pull request with the handler and processors that service already uses.

## Frequently asked questions

### Why keep the UidProcessor?

Because it is the correlation key. It puts one short id in `extra.uid` on every record written during a request, so the request record from the new middleware, an action's info line and an error record can be grouped in a log viewer. Without it, JSON lines are structured but unrelated to each other.

### Why does Slim's error handler need the logger passed in?

Slim 4.12's `ErrorHandler` takes an optional `LoggerInterface` and otherwise uses its own `Slim\Logger`, which calls PHP's `error_log`, so with `logError` on, exceptions would land in the web server's error log as text. `public/index.php` constructs the handler and the error middleware itself, so passing the container's logger into both is two arguments.

### Can I keep readable logs in development?

Yes. The `format` key in the `logger` settings takes `json` or `line`; `line` keeps Monolog's default text output with the same processors attached. The test for the JSON shape builds its own handler, so it passes whichever value the settings hold.

### Does the request record include the response time for error responses?

Yes. The error middleware is added last in `public/index.php`, so it is outermost and `RequestLoggingMiddleware` sits inside it; an exception becomes a response before it passes back through the new middleware, which logs the status and the elapsed milliseconds like any other response. The `404` test is what shows it.

## More Slim jobs

- [Add Twig Templates to a Slim 4 App](https://getrush.ai/run/add-twig-views/slim/)
- [Upgrade PHPUnit in a Slim 4 App](https://getrush.ai/run/upgrade-phpunit/slim/)
- [Write the Missing PHPUnit Tests for a Slim 4 API](https://getrush.ai/run/write-unit-tests/slim/)

## The same job on other stacks

- [Add Structured Logging to a Socket.IO Server](https://getrush.ai/run/add-structured-logging/socket-io/)
- [Add Structured Logging to a Temporal TypeScript Worker](https://getrush.ai/run/add-structured-logging/temporal/)
- [Add Structured JSON Logging to a Tokio Server](https://getrush.ai/run/add-structured-logging/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/)
