# Add Structured Logging to a Node.js App from a Linear Issue

Yes. Label the Linear issue and an agent swaps console.log for a JSON logger in your Express app, redacts secrets, logs each request and opens a PR linking it.

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

## What the agent does

The agent reads the issue, then finds every place the app logs. In an Express 4 app shaped like OWASP/NodeGoat, a grep for `console.` across server.js, app/routes and app/data finds 29 calls. server.js logs the MongoDB connection and the port; app/routes/error.js prints `err.message` and `err.stack` from the error middleware; app/routes/session.js logs `redirecting to login` from two middlewares and `Error: attempt to login with invalid user:` followed by the raw user name, next to a long comment about CRLF log injection; and each DAO in app/data logs `Updated allocations` or a warning when its constructor is called without `new`. The worst line is in config/config.js: at startup it prints the whole merged config with `util.inspect`, including `cookieSecret` and `cryptoKey` from config/env/all.js. There is no logging library in package.json at all.

Picking the library means reading the runtime constraints first. The Dockerfile pins `node:12-alpine`, .github/workflows/e2e-test.yml runs Cypress on Node 10, 12 and 14, and lint.yml runs jshint 2.12.0 on Node 14 with the double-quote, four-space and strict-mode rules in .jshintrc. So the agent chooses a pino release whose `engines` field accepts those versions, checks it with `npm view`, and adds it with pino-http at matching versions. It writes app/logger.js that creates one logger with a `redact` list covering `cookieSecret`, `cryptoKey`, `password`, `req.headers.cookie` and `req.headers.authorization`, and a level read from `LOG_LEVEL` with a default of info.

Then it replaces the calls. config/config.js logs the environment name and the config with secrets redacted instead of the raw dump. server.js logs the database connection and the listening port as structured fields. error.js logs the error object under `err` so pino's serializer records the message and stack as fields rather than two unstructured lines. The login failure in session.js logs the user name as a field, which answers the CRLF comment above it: a JSON encoder escapes a newline inside a string, so a crafted user name cannot forge a second log line. The DAO messages become debug-level events with the collection name. pino-http is mounted before the routes in server.js so every request gets a line with method, URL, status and duration and a request id, and the middleware is placed after the static handler so asset requests do not flood the log.

It tests what it changed. Gruntfile.js already has a `mochaTest:unit` target over test/unit/*.js that matches nothing today, so the agent adds test/unit/logger-test.js: it builds the logger with a writable stream as destination, logs an object containing `cookieSecret` and a user name with an embedded newline, and asserts that the output is one line of valid JSON with the secret replaced and the newline escaped. It runs `npx jshint .` as lint.yml does, since the new files must use double quotes and `use strict`, and brings the app up against a MongoDB container with `npm run db:seed` and `npm start` to read the request log for a login and a profile page. The pull request links the issue, lists every replaced call by file and line, and shows a sample of the new output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "A Linear issue labelled agent asks for structured JSON logging in this Express app, with no secrets in the logs. Read package.json, server.js, config/config.js, config/env/all.js, app/routes/index.js, app/routes/error.js, app/routes/session.js, every file in app/data, Gruntfile.js, .jshintrc, Dockerfile and the workflows under .github/workflows first, and list every console call with its file and line. Choose a pino and pino-http release whose engines field accepts the Node versions the Dockerfile and the CI matrix use, confirm with npm view, and add them. Create app/logger.js with redaction for cookieSecret, cryptoKey, password, the cookie header and the authorization header, and a level from LOG_LEVEL. Replace every console call, log errors under the err key, log the login user name as a field, and stop config.js from printing the merged config with secrets. Mount pino-http after the static handler and before the routes. Add test/unit/logger-test.js that captures the logger output and asserts the secret is redacted and an embedded newline is escaped, run npx jshint ., npm test, and start the app against MongoDB to capture sample request lines. Open a pull request that links the issue, lists the replaced calls and quotes the sample output.",
  "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 that adds pino and pino-http to package.json and package-lock.json, a new app/logger.js, a new test/unit/logger-test.js, and edits to server.js, config/config.js, app/routes/error.js, app/routes/session.js and the DAO files, with every former console call listed in the description by file and line beside what replaced it. The issue is linked at the top.

The description quotes a few lines of the new output from the sandbox: a startup line with the environment and port, a request line for a login with method, path, status and response time, and the redacted config dump showing `[Redacted]` where the secrets were. It quotes the `npx jshint .` result and the mocha run with the new unit test named, and says which pino version was chosen and the Node range its engines field declares.

Before merging, a reviewer checks the redact list against config/env/all.js and the session middleware, decides whether `req.headers.cookie` should be dropped or redacted, and reads the login failure line to confirm the user name is a field rather than concatenated text. A request to change the log level per environment is a follow-up on the same session.

## Run it on every Linear issue labelled agent

Sign in to Linear once with `POST /me/connections {"type": "app", "name": "linear"}` and finish the authorize URL in the console. Then add an automation to the Project with this prompt and a `linear` trigger on `linear.issue.labeled`, naming the label in `config.labels`. The trigger adds the issue after the prompt, so an issue that says which fields must never appear in logs, or which routes are too noisy to log, reaches the agent as its instructions. Changes made by an app integration never fire the trigger.

Each labelled issue gets its own sandbox and its own pull request, and the automation's `max_runs_per_hour` caps the rate. A team working through a backlog of hardening issues can label one at a time and review one pull request at a time, each linked to the issue that asked for it.

## Why run it on Rush?

Replacing 29 log calls is not hard; proving that no secret and no forged line can reach the log is. That proof is a test that writes a secret and a newline through the real logger and reads the bytes back, plus a running app whose request log a reviewer can read. The agent does both in its own sandbox with a MongoDB container beside it, and the version choice is checked against the CI matrix rather than assumed, because a logger that drops Node 10 would fail the e2e workflow on its first run.

The record stays with the pull request: the grep that found every call, the `npm view` that confirmed the engines range, the jshint run, the unit test and the sample output are all in the run's transcript. Nothing touches the default branch; a reviewer merges when the redact list matches what their config actually holds.

## Frequently asked questions

### Why pino rather than winston?

pino writes one JSON object per line with a serializer for errors and a built-in redact option, which is exactly what the issue asks for, and pino-http gives request logging with the same format. If the issue names winston instead, the agent uses it; the redaction then comes from a format function and the pull request shows the equivalent test.

### Will it break the Node 10 and 12 CI jobs?

The agent picks a release whose engines field accepts every version in the e2e matrix and the Dockerfile, and shows the npm view output in the pull request. If no current release supports the oldest version, it says so and proposes dropping that matrix entry as a separate decision rather than silently pinning an old logger.

### What happens to the config dump at startup?

config/config.js currently prints the entire merged config with util.inspect, including cookieSecret and cryptoKey. The agent replaces it with a single log event that passes the config through the logger's redact list, so the keys appear with a placeholder value and the secrets never reach stdout.

### Does this fix the log injection the comments describe?

It removes the specific risk: the user name is logged as a JSON field, and a JSON encoder escapes carriage returns and newlines, so a crafted name cannot start a second line. The unit test asserts that. Encoding for HTML or URLs, which the comments also mention, is a separate concern for the templates, not the logger.

### Can it skip logging for health checks or static assets?

Yes. pino-http is mounted after express.static so asset requests are not logged, and the prompt or the issue can name paths to ignore; the agent adds an autoLogging ignore for them and says so.

## More Node.js jobs

- [Convert a Node.js App from JavaScript to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/nodejs/)
- [Fix "DeprecationWarning: Buffer() is deprecated" (DEP0005) in Node.js](https://getrush.ai/run/fix-buffer-deprecation-warning/nodejs/)
- [Fix "[DEP0147] DeprecationWarning: fs.rmdir(path, { recursive: true }) will be removed" in Node.js](https://getrush.ai/run/fix-fs-rmdir-recursive-deprecation-warning/nodejs/)

## The same job on other stacks

- [Add Structured Logging to a Phoenix LiveView App](https://getrush.ai/run/add-structured-logging/phoenix-liveview/)
- [Add Structured Logging to a Quarkus App](https://getrush.ai/run/add-structured-logging/quarkus/)
- [Add Structured Logging to a React Router App With a Custom Express Server](https://getrush.ai/run/add-structured-logging/react-router/)

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