# Add Structured JSON Logging to a Vapor App

Yes. An agent adds a swift-log JSON handler to your Vapor app, bootstraps it in production only, keeps console logs in development, and opens a tested pull request.

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

## What the agent does

The agent clones the repository into its own cloud sandbox and reads how logging is set up before it writes a handler. In a project generated from vapor/template, `entrypoint.swift` calls `Environment.detect()`, then `LoggingSystem.bootstrap(from: &env)`, which installs Vapor's console handler at the level the `--log` flag or `LOG_LEVEL` names, and reports a failed start with `app.logger.report(error:)`. `Package.swift` is on swift-tools 6.3, Vapor from 4.121.4 and swift-nio from 2.101.0, and turns on upcoming features such as `ExistentialAny` and `MemberImportVisibility`, which the new code has to compile under. `docker-compose.yml` passes `LOG_LEVEL: ${LOG_LEVEL:-debug}` and starts the app with `serve --env production`, so production and development already differ in exactly the way the handler needs.

It adds `Sources/App/Logging/JSONLogHandler.swift`, a `LogHandler` from swift-log that writes one JSON object per line: the timestamp, `level`, the logger `label`, the `message`, the merged `metadata`, and `source`. Vapor gives every `req.logger` a `request-id` in its metadata, so each line that a route handler or `RouteLoggingMiddleware` writes carries the id without any change to the controllers. Values are escaped through `JSONEncoder` rather than string interpolation, so a title with a quote in it cannot break a line, and the handler keeps `logLevel` and `metadata` as stored properties, which is what `LogHandler` requires.

In `entrypoint.swift` the bootstrap becomes a branch: when `env == .production` it calls `LoggingSystem.bootstrap` with a factory that returns the JSON handler at the level read from `LOG_LEVEL`, and otherwise it keeps `bootstrap(from:)`, so `swift run` in development and the `.testing` environment in `AppTests.swift` still print the readable console format. `LoggingSystem.bootstrap` may run once per process, so the tests never call it; the agent writes a test that constructs the handler over an in-memory stream, logs one message with metadata, decodes the line with `JSONDecoder` and asserts the keys, and a second test that an unsupported `LOG_LEVEL` value falls back to the default instead of crashing.

Then it proves the change end to end: `swift build` and `swift test` in the sandbox, and `docker compose build` followed by `docker compose up app`, reading the container's output to confirm that the startup line and a `GET /todos` request each arrive as one JSON object with `request-id`. It opens a pull request with the handler, the entrypoint change, the tests and a note in the README on the `LOG_LEVEL` values.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add structured JSON logging to this Vapor app. Read Package.swift, Sources/App/entrypoint.swift, configure.swift, routes.swift, the controllers, docker-compose.yml, the Dockerfile and the tests first. Write a swift-log LogHandler that emits one JSON object per line with the timestamp, level, label, message, metadata and source, and bootstrap it only when the environment is production, keeping Vapor's console logger in development and testing. Honour LOG_LEVEL the way the console logger does. Add Swift Testing tests that decode a line written by the handler and check its keys, without bootstrapping the logging system in tests. Run swift build and swift test, start the production image with docker compose and confirm the request log lines are JSON, and 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

What comes back is a pull request on its own branch. The diff adds `Sources/App/Logging/JSONLogHandler.swift`, changes the bootstrap lines in `entrypoint.swift`, adds the two tests to the app's test target and a short README section on `LOG_LEVEL`. No controller, model or migration changes, because the request id already travels in the logger's metadata.

The run's record keeps `swift build`, the `swift test` output with the existing todo tests and the two new ones, and the `docker compose up app` output showing the JSON startup and request lines, so a reviewer can read a real line before approving the format.

Before merging, a reviewer checks that the field names match what the log pipeline expects, that the handler is installed only for `.production`, and that `LOG_LEVEL` in `docker-compose.yml` still takes effect, since the compose file defaults it to `debug`.

## Run it on every new Vapor service

A team with several Vapor services starts one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. Each run reads its own `entrypoint.swift`, so a service that already customises the bootstrap gets the JSON handler folded into it rather than a second bootstrap, and each opens its own pull request.

A `request_id` in the body makes a retry safe, and the API key's webhook posts `run.completed` or `run.failed` with the `session_url` when each turn ends, so a script can collect the pull request links and the sample log lines.

## Why run it on Rush?

A log format is only right when a line from the real binary parses, and that means building the release image and reading its output. The sandbox has the Swift toolchain and Docker, so the agent runs `swift test` and the production container and keeps every line it saw, instead of a reviewer trusting a handler from its source.

The change is small but it sits at the process entry point, where a mistake takes the whole service down at startup. One run returns one pull request with the handler, the guard and the tests, and the same prompt runs against every Vapor service at once, each in its own sandbox.

## Frequently asked questions

### Why write a handler instead of adding a package?

swift-log ships no JSON handler, and one over the `LogHandler` protocol is short. Writing it keeps the dependency list of `Package.swift` unchanged and lets the reader choose the exact field names. If the team already standardises on a logging package, the prompt can name it and the agent wires that instead.

### Will development logs become JSON too?

No. The branch in `entrypoint.swift` installs the JSON handler only for `.production`. `swift run`, `--env development` and the `.testing` environment the tests use keep the console handler, so local output stays readable.

### Does the request id come through?

Yes. Vapor attaches a `request-id` to each request's logger metadata, and the handler writes metadata into every line, so `RouteLoggingMiddleware` lines and anything a controller logs through `req.logger` share the id.

### Can the log level still be changed at runtime?

The level is read once at startup from `LOG_LEVEL`, as the console logger does, so changing it means restarting the container with a new value. The compose file already passes the variable through.

## More Vapor jobs

- [Add Pagination to a Vapor API from a Linear Issue](https://getrush.ai/run/add-todo-pagination/vapor/)
- [Add User Registration to a Vapor App](https://getrush.ai/run/add-user-registration/vapor/)
- [Add a WebSocket Endpoint to a Vapor App from a Linear Issue](https://getrush.ai/run/add-websockets/vapor/)

## The same job on other stacks

- [Add Structured Logging to an Actix Web App](https://getrush.ai/run/add-structured-logging/actix/)
- [Add Structured Logging to an aiohttp App](https://getrush.ai/run/add-structured-logging/aiohttp/)
- [Add Structured Logging to an Axum API](https://getrush.ai/run/add-structured-logging/axum/)

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