# Add Structured Logging to a Sequelize App

Yes. An agent routes your Sequelize query log and Express request log through pino as JSON lines with a request id and query timing, tests the shape, and opens a PR.

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

## What the agent does

The agent starts by finding where the app logs today, because a structured logger that misses the query log leaves the noisiest lines unchanged. In a Sequelize app laid out like sequelize/express-example, `sequelize/index.js` builds the connection with `dialect: 'sqlite'`, `logQueryParameters: true` and `benchmark: true` and no `logging` option, so Sequelize prints every statement with its parameters and timing through `console.log`. `index.js` uses `console.log` for the connection check and the port, `express/app.js` mounts `body-parser` and the routes and has no request log at all, and errors travel through `makeHandlerAwareOfAsyncErrors` to `next(error)` and Express's default handler, which answers an HTML stack trace. `express/helpers.js` throws a `TypeError` for a non-numeric `:id`, so `/api/users/abc` is a 500 today. There is no test script, no lockfile (`.npmrc` sets `package-lock=false`), and `engines` says Node 10 or newer.

Then it adds the logger. `logger.js` at the root exports one `pino` instance whose level comes from `LOG_LEVEL` with `info` as the default. `sequelize/index.js` gets `logging: (sql, timingMs) => logger.debug({ sql, durationMs: timingMs }, 'query')`: with `benchmark: true` Sequelize passes the elapsed milliseconds as the second argument, and `logQueryParameters` keeps the bound values in `sql`, so each statement becomes one JSON line a log store can index by duration. `index.js` logs the connection check and the listening port through the same instance, and the `process.exit(1)` on a failed `authenticate()` is preceded by a line at `fatal` with the error.

The request log comes from `pino-http` in `express/app.js`, mounted before the routes with `genReqId` so every request carries `req.id`, and the handler wrapper is extended so the error it passes to `next` is logged at `error` with that id. A small error middleware at the end of `app.js` answers JSON (`{ error, requestId }`) instead of the HTML page, with 400 for the `TypeError` the id helper throws and 500 for everything else. The `/` route and the REST routes are otherwise untouched.

Last it proves the lines. The agent adds a `test` script using Node's built-in test runner and `supertest`, and `test/logging.test.js`, which builds the app with a pino destination that writes to an in-memory stream, runs `npm run setup-example-db` once, requests `/api/orchestras?includeInstruments` and `/api/users/abc`, and asserts that each line parses as JSON, that the request line carries `req.id`, that a `query` line carries `durationMs` and `sql`, and that the bad id answers 400 with a `requestId` matching the log. It runs that test and starts the server once to paste a real line into 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 Sequelize and Express app. Read index.js, express/app.js, express/helpers.js, the three route files, sequelize/index.js, sequelize/extra-setup.js, the model files, sqlite-example-database/setup.js, package.json and .npmrc first. Add pino with a single logger module, pass a logging callback to the Sequelize constructor that logs each query as one JSON line with the SQL and the benchmark timing, and replace the console.log calls in index.js. Mount pino-http in express/app.js with a request id, log errors from the async handler wrapper with that id, and add an error middleware that answers JSON with the request id, 400 for the TypeError from getIdParam and 500 otherwise. Add a test script using node:test and supertest that captures the log stream and checks the line shape and the 400 case. Run the test, start the app once to capture a real line, and open a pull request with the output. Keep the REST routes' responses unchanged for successful 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

The pull request changes `index.js`, `express/app.js`, `sequelize/index.js` and `package.json`, and adds `logger.js` and `test/logging.test.js`. Its description shows one captured request line and one query line from the sandbox, the test output, and a note on which Node versions the chosen `pino` release supports against the `>=10` in `engines`.

There is no workflow in this repository, so nothing runs on the pull request; the test command in `package.json` is what a reviewer runs locally and what a later CI job would call.

Before merging, a reviewer decides whether query logging belongs at `debug` or `info` in production, whether `logQueryParameters` should stay on where the parameters may hold personal data, and whether the JSON error body is the shape their clients expect, since the plain-text `404 - Not found` responses in the routes are left as they were.

## Run it on every service that still logs with console.log

A team that keeps several Express services on Sequelize 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 its own `Sequelize` constructor, so a service already passing a `logging` function gets it redirected rather than replaced, and one on Postgres gets the same callback with its own dialect untouched.

A team that tracks platform work in Linear runs the same prompt from an automation in the Project with a `linear` trigger on issues labelled `logging`. The trigger adds the issue after the prompt, so an issue that names the log fields the team's collector expects, or asks for `pino-pretty` in development, reaches the agent with that request, and the pull request links back to it.

## Why run it on Rush?

The claim behind this change is that every line the service writes is JSON a collector can parse, and the only way to check it is to run the app and read what comes out. The agent does that in its own sandbox: it resets the SQLite example database, makes real requests, and captures the stream, so the lines in the pull request are the ones the service will print, not the ones the code looks like it prints.

The test it adds runs the same assertions on every future change, and the run keeps the full command output, so a reviewer sees the test pass without pulling the branch. For a team with many services, each gets its own run and its own pull request, fitted to its own constructor and routes.

## Frequently asked questions

### Does Sequelize really pass the query time to the logging function?

Yes, when `benchmark: true` is set, which this app already does. Sequelize then calls `logging(sql, timingMs)` with the elapsed milliseconds as the second argument; without `benchmark` the second argument is the query options object. The callback the agent writes reads it as a number and names it `durationMs`.

### Will this change what the API returns?

Successful responses are unchanged. What changes is the error path: an unhandled error answered Express's HTML stack page before and answers a JSON body with a `requestId` now, and a malformed `:id` answers 400 rather than 500. The pull request lists both so a client that depended on the old status can be checked.

### Why pino rather than winston?

pino writes one JSON line per call with no formatting layer in between, which is what a collector wants, and `pino-http` gives the request log and the id in one middleware. The agent checks the chosen release's `engines` field against the `>=10` in this app's `package.json` and says in the pull request which Node version the service needs.

### There is no lockfile here; does the agent add one?

No. `.npmrc` sets `package-lock=false`, which is a choice the repository made, so the agent installs within it and adds the new dependencies to `package.json` with caret ranges. The pull request notes the installed versions so a reviewer can pin them if they prefer.

## More Sequelize jobs

- [Add Transactions to a Sequelize App](https://getrush.ai/run/add-transactions/sequelize/)
- [Convert a Sequelize Express App to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/sequelize/)
- [Fix "TypeError: sequelize.import is not a function" after upgrading to Sequelize 6](https://getrush.ai/run/fix-sequelize-import-is-not-a-function/sequelize/)

## The same job on other stacks

- [Add Structured Logging to a Serverless Framework API from a Linear Issue](https://getrush.ai/run/add-structured-logging/serverless/)
- [Add Structured Logging to a Slack Bolt App](https://getrush.ai/run/add-structured-logging/slack-bolt/)
- [Add Structured Logging to a Slim 4 App](https://getrush.ai/run/add-structured-logging/slim/)

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