# Add Slow Query Logging to a TypeORM + NestJS App

Yes. An agent sets TypeORM's maxQueryExecutionTime, routes its logger through Nest's so slow queries land in your app log with their SQL, and opens a PR.

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

## What the agent does

The agent reads how the connection is configured before it adds a logger, because TypeORM's logging lives on the connection options. In an app laid out like lujakob/nestjs-realworld-example-app, `ApplicationModule` in `src/app.module.ts` calls `TypeOrmModule.forRoot()` with no arguments, so TypeORM reads `ormconfig.json` from the project root; `ormconfig.json.example` is a MySQL config with the host, credentials, `entities: ["src/**/**.entity{.ts,.js}"]` and `synchronize: true`, and `.gitignore` excludes the real `ormconfig.json` and `src/config.ts`. `package.json` pins `typeorm` ^0.2.24 and `@nestjs/typeorm` ^7, `index.js` starts the app through `ts-node/register`, and `src/tag/tag.controller.spec.ts` also calls `TypeOrmModule.forRoot()`, so any change to how options are loaded has to keep that test compiling. Nothing in the app logs a query today: the only logging is the `console.log` Nest prints at bootstrap.

TypeORM 0.2 has the feature built in: a `maxQueryExecutionTime` option in milliseconds makes every query that runs longer than it reach the logger's `logQuerySlow` method with the time, the SQL and the parameters, and that call is made whether or not the `logging` list includes `query`. So the smallest change is two keys in `ormconfig.json`: `maxQueryExecutionTime` set to 500 and `logging` set to `["error", "warn"]`, so failed queries and slow ones print and routine ones do not. The agent makes that change in `ormconfig.json.example`, which is what the README tells a developer to copy, and explains in the pull request that the built-in `advanced-console` logger prints a slow query as a `query is slow` line with the execution time, the statement and the parameters.

Because the console logger's output does not match the Nest log lines around it, the agent also adds `src/shared/typeorm-nest.logger.ts`, a class implementing TypeORM's `Logger` interface that forwards `logQuerySlow` to a Nest `Logger` from `@nestjs/common` at `warn` level with the time in milliseconds, the SQL and the parameter count, `logQueryError` at `error`, `logMigration` and `logSchemaBuild` at `log`, and leaves `logQuery` as a no-op. A class cannot be named in a JSON file, so `app.module.ts` moves to `TypeOrmModule.forRootAsync` with a `useFactory` that spreads the result of TypeORM's `getConnectionOptions()`, which still reads `ormconfig.json`, and adds `logger: new TypeOrmNestLogger()` and `maxQueryExecutionTime` from a `TYPEORM_SLOW_QUERY_MS` environment variable, default 500. The tag spec keeps its bare `forRoot()` and keeps working, because the JSON file still holds everything it needs. Parameters are logged as a count, not values, so an email or a password hash bound to a slow `INSERT` never reaches the log.

To see a slow line, the agent installs MariaDB with `apt-get` in its sandbox, creates the `nestjsrealworld` database the README names, copies both example files into place, runs `npm install` and starts the app with `TYPEORM_SLOW_QUERY_MS=0` so every query qualifies, registers a user and lists articles, and reads the warnings Nest prints, with the Nest timestamp and context in front of the SQL. It adds `src/shared/typeorm-nest.logger.spec.ts`, which needs no database: it calls `logQuerySlow` with a fake query runner and asserts on a spied Nest `Logger.warn`, and runs `npm test` under the existing `jest.json`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add slow query logging to this NestJS + TypeORM app. Read package.json, index.js, jest.json, .gitignore, ormconfig.json.example, src/main.ts, src/app.module.ts, src/tag/tag.controller.spec.ts and the README first. Set maxQueryExecutionTime to 500 and logging to error and warn in ormconfig.json.example and explain in the pull request that TypeORM calls logQuerySlow for any query over that time regardless of the logging list. Add src/shared/typeorm-nest.logger.ts implementing TypeORM's Logger interface, forwarding logQuerySlow to a Nest Logger at warn with the time, the SQL and the number of parameters but never their values, logQueryError at error, logMigration and logSchemaBuild at log, and logQuery as a no-op. Move app.module.ts to TypeOrmModule.forRootAsync with a useFactory that spreads getConnectionOptions() and adds the logger and maxQueryExecutionTime read from TYPEORM_SLOW_QUERY_MS, default 500, so the tag spec's bare forRoot() keeps working. Add src/shared/typeorm-nest.logger.spec.ts that spies on Logger.warn without a database. Install MariaDB in your sandbox, create the nestjsrealworld database, copy the example config files, run npm install, start the app with TYPEORM_SLOW_QUERY_MS=0, register a user, list articles, and paste the slow query warnings and the npm test output into the pull request. Change no entity, route or response.",
  "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 adds `src/shared/typeorm-nest.logger.ts` and its spec, and changes `src/app.module.ts`, `ormconfig.json.example` and the README's config section. Its description pastes the `npm test` summary and a handful of warnings from the sandbox run with the threshold at zero, each a Nest-formatted line with the execution time, the statement and the parameter count, so the reviewer sees the exact shape of what will appear in production logs before a real slow query does.

With the default threshold, a deployment logs nothing new until a query takes longer than 500 milliseconds, and `TYPEORM_SLOW_QUERY_MS` moves that line without a code change. The description names the one structural change, `forRoot()` to `forRootAsync` with `getConnectionOptions()`, and shows that the existing tag spec still passes with its bare `forRoot()`.

Before merging, a reviewer picks the threshold for their database, decides whether `error` and `warn` is the right `logging` list for the environments they run, and confirms that a parameter count rather than parameter values is the privacy line they want.

## Run it on every service with no query timings

An engineer who suspects a slow query but cannot see one starts this from the terminal with this body and comes back to a pull request. One `POST /o/{org}/sessions` per TypeORM service, each with its own `resources` URL; the run reads how each service loads its connection options, so a service with a TypeScript `ormconfig` or options in code gets a different diff from this JSON-based one.

Send a `request_id`, a UUID, with each body so a retried call returns the run it already started. A key runs at most `max_concurrent` sessions at once, 4 by default, and a request past that answers `202` with `status: "queued"` and starts when a slot frees. A `webhook_url` on the key brings `run.completed` for each run the key started, with `data.session_url` to read for the pull request link.

## Why run it on Rush?

Logging changes are judged by what they print, and the only way to see that is to run the app against a real database and make a query cross the threshold. The agent does that in its own sandbox, with MariaDB installed and the threshold at zero, and pastes the lines, so the reviewer judges the real output rather than a description of it.

The transcript keeps every command and its output, so the reviewer reads the startup, the requests and the warnings without checking the branch out. Several services can be instrumented at once, each run in its own sandbox with its own database, and nothing merges until a person reads the diff.

## Frequently asked questions

### Do I need the custom logger, or is maxQueryExecutionTime enough?

`maxQueryExecutionTime` alone works with TypeORM's built-in `advanced-console` logger and prints a `query is slow` line. The custom class exists so the line carries Nest's timestamp and context like the rest of the log and can be shipped by whatever reads Nest's output. The pull request makes the two-key change first and the class second, so either can be taken alone.

### Why move forRoot() to forRootAsync?

A logger is a class instance, and `ormconfig.json` can only hold strings and numbers. `forRootAsync` with `getConnectionOptions()` keeps reading the JSON file for everything else and adds the two options in code. The tag spec's bare `forRoot()` still reads the same file, which is why it keeps passing.

### Will parameter values end up in the log?

No. `logQuerySlow` receives the parameters, and the custom logger logs their count. The built-in console logger prints the values, which is why the custom class is the one the agent wires in by default and why the pull request says so.

### Does logging every slow query cost anything?

TypeORM measures every query's time whenever `maxQueryExecutionTime` is set and calls the logger only past the threshold, so the cost is one timing per query. `logQuery` is a no-op in the custom class, and `logging` is limited to `error` and `warn`, so routine queries produce nothing.

## More TypeORM jobs

- [Add Soft Delete to TypeORM Entities](https://getrush.ai/run/add-soft-delete/typeorm/)
- [Wrap Multi-Step Writes in TypeORM Transactions](https://getrush.ai/run/add-transactions/typeorm/)
- [Fix Type Has No Properties in Common With FindOneOptions After a TypeORM Upgrade](https://getrush.ai/run/fix-type-has-no-properties-in-common-with-findoneoptions/typeorm/)

## The same job on other stacks

- [Add Slow Query Logging to a Drizzle App](https://getrush.ai/run/add-slow-query-logging/drizzle/)
- [Add Slow Query Logging to a GORM App](https://getrush.ai/run/add-slow-query-logging/gorm/)
- [Add Slow Query Logging to a Mongoose App](https://getrush.ai/run/add-slow-query-logging/mongoose/)

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