# Add Structured Logging to a Koa API

Yes. An agent turns a Koa API's winston logs into JSON lines with request id, route, status and duration on stdout, keeps dev output readable, tests it, in a PR.

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

## What the agent does

The agent reads the logger that exists before it writes one. In an API like javieraviles/node-typescript-koa-rest, `src/logger.ts` exports a middleware factory that reconfigures the global `winston` instance each time it is called: a `File` transport writing errors to `error.log` next to the compiled code and a `Console` transport with `format.colorize()` and `format.simple()`, then logs one string per request, `${ctx.method} ${ctx.originalUrl} ${ctx.status} ${ms}ms`, at a level chosen by status. The same middleware catches errors and writes `err.message` into the response body. `src/server.ts` calls `app.use(logger(winston))` second, after `koa-helmet`, and uses `console.log` for the startup line and the TypeORM connection failure; `src/cron.ts` logs with `console.log` too. `src/config.ts` derives `debugLogging` from `NODE_ENV=development`. `package.json` has winston `^3.3.3`, koa `^2.13.1`, `@koa/router`, jest 26 with ts-jest, and a `lint` script of `tsc --noEmit` then eslint with double quotes and semicolons enforced by `.eslintrc`; the `Dockerfile` runs `npm run start` on `node:14-alpine`.

The agent replaces the factory with one logger. `src/logger.ts` creates a `winston.createLogger` with `format.timestamp()`, `format.errors({ stack: true })` and `format.json()` on a single `Console` transport, so each line is a JSON object, and switches to `format.colorize()` with `format.simple()` only when `config.debugLogging` is true, so local output stays readable. The file transport goes: on Heroku and in the container the disk is ephemeral and stdout is what the platform collects. The request middleware becomes `requestLogger`, which reads an incoming `X-Request-Id` or makes one with `crypto.randomUUID()`, sets it on `ctx.state.requestId` and echoes it in the response header, times the handler with `process.hrtime.bigint()`, and logs one object per request with `requestId`, `method`, `path`, `route` (the matched pattern from `@koa/router`, so `/users/:id` is one value), `status`, `durationMs`, `ip` and `userAgent`.

Errors keep their behaviour and gain their context. The middleware still sets the status and body the way the old one did, but logs the error object itself so the JSON line carries `stack`, and the pull request notes that returning `err.message` to clients is unchanged and worth a separate decision. `ctx.state.log` is a child logger with the request id attached, so a controller such as `src/controller/user.ts` can log inside a handler and the line joins the request's trace. `src/server.ts` and `src/cron.ts` lose their `console.log` calls in favour of the logger, which means the TypeORM connection error also arrives as JSON with a stack.

Tests use the repository's jest setup. `tests/logger.test.ts` builds a Koa app with the middleware and a winston transport that captures entries in an array, makes requests with Node's `http` module against an ephemeral port, and asserts the fields, the echoed header, the reuse of an incoming id, and that an error path logs at `error` with a stack. The agent runs `npm run lint` (the TypeScript check and eslint) and `npm test`, and starts the compiled server once with `NODE_ENV=production` to show a real line. The repository's `ci.yml` names a runner label GitHub has retired, so until that is fixed the checks that count are the ones the pull request quotes from the sandbox.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add structured logging to this Koa API. Read src/logger.ts, src/server.ts, src/config.ts, src/cron.ts, src/controller/user.ts, src/protectedRoutes.ts, src/unprotectedRoutes.ts, package.json, .eslintrc, tsconfig.json, Dockerfile and tests/controller/user.test.ts first. Replace the winston reconfiguration in src/logger.ts with one createLogger instance: timestamp, errors with stack and json format on a single Console transport, and colorize plus simple only when config.debugLogging is true; drop the file transport. Add a requestLogger middleware that reads or creates an X-Request-Id with crypto.randomUUID, stores it on ctx.state.requestId, echoes it in the response header, times the handler, and logs one object per request with requestId, method, path, route pattern from the router, status, durationMs, ip and userAgent, keeping the existing error-to-response behaviour and logging the error object with its stack. Provide ctx.state.log as a child logger with the request id. Replace console.log in src/server.ts and src/cron.ts with the logger. Add tests/logger.test.ts with a capturing transport that asserts the fields, the header echo, reuse of an incoming id, and the error path. Run npm run lint and npm test until they pass, start the built server once with NODE_ENV=production to capture a sample line, then open a pull request that shows a development line and a production line side by side.",
  "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 `src/logger.ts`, `src/server.ts` and `src/cron.ts`, adds `tests/logger.test.ts`, and removes `error.log` from the paths the code writes to. Its description shows the same request logged twice, once in development with colours and once in production as one JSON object, lists every field with where it comes from, and quotes the `npm run lint` and `npm test` output from the sandbox.

It names the behaviours it kept on purpose: the response body on an error is still `err.message`, the log level by status (`error` at 500 and above, `warn` at 400 and above) is unchanged, and the request id header name is `X-Request-Id` so a proxy that already sets one is honoured. It also says what it did not do: no log shipping, no sampling, and no change to TypeORM's own `logging: false`.

Before merging, a reviewer decides whether internal error messages should keep reaching clients, whether the platform's log collector expects a particular timestamp field name, and whether TypeORM query logging should be routed through the same logger with its `logger` option.

## Run it on every Node service that still logs strings

A team with several Node 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 logger: a service on pino gets the request fields through its own serializers, an Express service gets the same middleware shape on `req` and `res`, and one that already emits JSON gets only the request id and the route pattern it lacks.

After the first merge, 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 a console.log or a string-formatted log line, post a review comment showing the equivalent call on the structured logger with the request id' starts one run per push. The trigger adds the pull request after the prompt and fills in nothing else, so the format holds as the codebase grows.

## Why run it on Rush?

Structured logging is a format decision plus a dozen small ones: which fields, where the request id comes from and whether it is echoed, how the route pattern replaces the raw path so logs group by endpoint, what happens to the file transport on a platform with no disk, and how to keep local output readable. The agent reads the existing middleware and the deployment files, makes each decision in the pull request, and proves the fields with a test that captures real log entries.

The sample lines, the test output and the diff stay with the run, so a reviewer sees the exact JSON a log collector will receive. A team with several services runs the same request across all of them at once.

## Frequently asked questions

### Will development output become unreadable JSON?

No. When `config.debugLogging` is true, which `src/config.ts` sets from `NODE_ENV=development`, the logger uses colours and the simple format. JSON is used everywhere else, including the container built from the `Dockerfile`, where the platform reads stdout.

### Where does the request id come from?

From an incoming `X-Request-Id` header when a proxy or client sets one, otherwise from `crypto.randomUUID()`. It is stored on `ctx.state.requestId`, echoed in the response, and attached to `ctx.state.log`, so a controller's own log lines carry it without passing it around.

### What about TypeORM's query logs?

`src/server.ts` sets `logging: false`, and the pull request leaves it so. TypeORM accepts a custom `logger` in its connection options, and the description shows how to route its queries through the same winston instance when a team wants them, with the request id unavailable there because the pool is shared.

### Why remove the error.log file?

It was written next to the compiled code, which on Heroku and in the container is an ephemeral filesystem that disappears on restart, and it duplicated what the console transport already carried. One stdout stream of JSON lines is what log collectors expect, and the test proves the error path still records a stack.

## More Koa jobs

- [Fix Failing GitHub Actions Checks in a Koa API](https://getrush.ai/run/fix-failing-ci/koa/)
- [Move a Koa Project from Travis CI to GitHub Actions](https://getrush.ai/run/migrate-travis-to-github-actions/koa/)
- [Write Supertest Tests for a Koa App](https://getrush.ai/run/write-supertest-tests/koa/)

## The same job on other stacks

- [Add Structured JSON Logging to a Ktor Server](https://getrush.ai/run/add-structured-logging/ktor/)
- [Add Structured Logging to a Leptos Axum App](https://getrush.ai/run/add-structured-logging/leptos/)
- [Add Structured Logging to a Litestar App](https://getrush.ai/run/add-structured-logging/litestar/)

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