# Add a Request ID to Every Winston Log Line in an Express App

Yes. An agent adds a request id middleware, carries the id into every Winston and Morgan line with AsyncLocalStorage, echoes it in errors, and opens a PR.

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

## What the agent does

The agent reads how a line is written today. In a Node service laid out like hagopj13/node-express-boilerplate, `src/config/logger.js` builds one Winston logger whose `printf` format prints only `level: message`, with a console transport and `debug` level in development. `src/config/morgan.js` registers two Morgan handlers, one for responses under 400 logging through `logger.info` and one for the rest logging through `logger.error`, with a custom `:message` token read from `res.locals.errorMessage`, and `src/app.js` mounts them first, before Helmet and the body parsers. `src/middlewares/error.js` converts anything thrown into an `ApiError`, writes its message to `res.locals`, and sends `{ code, message }` with the stack only in development. So two overlapping requests produce interleaved lines that nothing ties together, and a user who reports an error has nothing to quote.

It adds the id in one place and reads it everywhere. A new `src/middlewares/requestId.js` takes an incoming `X-Request-Id` header when a proxy or client sent one and otherwise generates one; `package.json` declares `node >=12.0.0`, so the agent uses `crypto.randomBytes` rather than `randomUUID`, which that range does not promise, and says so. The middleware sets the same header on the response and runs the rest of the request inside an `AsyncLocalStorage` store from `async_hooks`, kept in a small `src/config/requestContext.js`. The logger gets a Winston format that reads the store and adds `requestId` to each `info`, and `printf` prints it in brackets when present, so a log line written from a model hook, a service or a `setTimeout` callback deep in a request still carries the id without any function passing it along.

Morgan and the error handler follow. A `:id` token in `morgan.js` reads the store so access lines carry the same id as the application lines inside them, the middleware is mounted in `app.js` ahead of the Morgan handlers so the first line of a request already has it, and `errorHandler` adds `requestId` to the JSON body, which is what a support reply can ask a user to paste. Nothing changes in the message format otherwise, so an existing log pipeline keeps parsing.

Tests sit where the project keeps them. A unit test beside `tests/unit/middlewares/error.test.js` uses `node-mocks-http` to call the middleware and assert a header comes back and a supplied one is reused, and an integration test with `supertest` through `app` asserts the response header on `/v1/docs` and `requestId` in a 404 body. The integration suite needs MongoDB, since `tests/utils/setupTestDB.js` connects on start, so the agent installs a MongoDB server in its sandbox and points `MONGODB_URL` at it. It runs `yarn test`, `yarn lint` with the Airbnb and security rules and `yarn prettier`, and keeps the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a request id to every log line. Read package.json, src/app.js, src/index.js, src/config/logger.js, src/config/morgan.js, src/middlewares/error.js, tests/unit/middlewares/error.test.js, tests/integration/docs.test.js and tests/utils/setupTestDB.js first. Add a middleware that reuses an incoming X-Request-Id header or generates one with crypto.randomBytes, sets it on the response, and runs the request inside an AsyncLocalStorage store. Add a Winston format that reads the store and prints the id in the existing printf format when present, a Morgan token so access lines carry it, and a requestId field in the error handler's JSON body. Mount the middleware before the Morgan handlers. Write a node-mocks-http unit test and a supertest integration test. Run yarn test against a local MongoDB, yarn lint and yarn prettier, and open a pull request with the output and a sample of the interleaved log lines from two concurrent requests.",
  "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/middlewares/requestId.js` and `src/config/requestContext.js`, changes `logger.js`, `morgan.js`, `error.js` and `app.js`, and adds two tests. The description shows the log output of two requests sent at once, each line prefixed with its own id, and the test, lint and format results.

The run's record keeps the test run against the real database, so a reviewer sees the integration test pass through the actual app and not a stub. A reviewer checks that the id survives into a line written after an `await` in a service, which is the case `AsyncLocalStorage` exists for, and that the header name matches what the team's proxy sets if it already sets one.

## Run it on every service that logs without a request id

A team with several Node services on this boilerplate starts one run per repository with one `POST /o/{org}/sessions` each, this prompt as `input` and the repository in `resources`. Each run reads its own `logger.js` and `app.js`, so a service that already logs JSON gets the id as a field in that JSON, and one that already sets a header reuses its name.

Send a `request_id` that is a UUID v5 of the repository's full name so a retried call returns the run it already started. The key's `webhook_url` reports when each run finishes, with `session_url` to read the pull request from.

## Why run it on Rush?

Everyone agrees logs need a request id and the work stalls on the plumbing: passing the id through every service call, or finding out whether the Node version in `engines` has the API that avoids that. The agent reads the version range, picks what it supports, wires the store once, and proves it with two real requests overlapping in its sandbox, so the pull request shows the interleaved lines sorted out by id rather than promising it.

The pull request is two small files and four edits, so review is reading the format function. A company with many services on this boilerplate runs them all at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why AsyncLocalStorage instead of passing req around?

Because the logger is called from models, services and hooks that never see the request, and threading it through every signature is the change nobody finishes. The store follows the async chain Node already tracks, so a line written after an `await` keeps the id. It is in `async_hooks` from Node 12.17, inside the range `engines` declares.

### Does it trust an incoming X-Request-Id?

It reuses one when present so the id matches what a proxy or a calling service logged, and it caps the length and allows only printable characters before using it, generating a fresh one otherwise. The description says which header name the agent chose and how to change it if the team's proxy uses another.

### Will log parsing break?

The line format stays `level: message` with the id added in brackets after the level, so a parser reading the level and message still does. A service already on JSON lines gets the id as a field instead, which the agent decides from its reading of `logger.js`.

### Why is the id in the error body?

So the person who hit the error can quote it. The body already carries a code and a message; the id is what turns a screenshot into the exact log lines, and it reveals nothing about the server.

## More Winston jobs

- [Migrate From Winston to Pino in a Node.js Service](https://getrush.ai/run/migrate-winston-to-pino/winston/)
- [Redact Tokens and Passwords from Winston Logs in an Express API](https://getrush.ai/run/add-log-redaction/winston/)
- [Add Log Rotation to a Winston Logger](https://getrush.ai/run/add-log-rotation/winston/)

## The same job on other stacks

- [Add Request ID Logging to an Actix Web App](https://getrush.ai/run/add-request-id-logging/actix/)
- [Add Request ID Logging to an AdonisJS App](https://getrush.ai/run/add-request-id-logging/adonisjs/)
- [Add Request ID Logging to an aiohttp App](https://getrush.ai/run/add-request-id-logging/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/)
