All jobs

Add Slow Query Logging to a Prisma App

Yes. An agent subscribes to Prisma's query events, logs every query over a threshold as one JSON line with its duration and target, and opens a pull request.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads how the client is built before it attaches a listener, because Prisma's log events are configured on the PrismaClient constructor and an app that constructs it in two places needs the listener in both. In an app laid out like the orm/express example in prisma/prisma-examples, package.json pins @prisma/client, prisma and @prisma/adapter-pg at 7.0.0 with pg 8.20.0, express 5.1.0, tsx and dotenv, and has one script, dev, that runs tsx src/index.ts. prisma/schema.prisma uses the prisma-client generator with output under prisma/generated, a PostgreSQL datasource, and two models: User with a unique email, and Post with createdAt, updatedAt, title, content, published, viewCount and an optional author. prisma.config.ts names the schema, the migrations path, a seed command of tsx prisma/seed.ts, and reads DATABASE_URL through env(). src/index.ts builds new PrismaPg({ connectionString }) and new PrismaClient({ adapter: pool }), and prisma/seed.ts builds its own pair the same way. The Express routes are POST /signup, POST /post, PUT /post/:id/views, PUT /publish/:id, DELETE /post/:id, GET /users, GET /user/:id/drafts, GET /post/:id and GET /feed, the last of which filters published posts with contains on title and content from a searchString query parameter and pages with skip and take. There are no tests in the example; the repository root runs vitest over the examples.

The client moves into one module. The agent writes src/prisma.ts that builds the adapter and the client once and exports it, with log set to [{ level: "query", emit: "event" }, { level: "warn", emit: "stdout" }, { level: "error", emit: "stdout" }], the shape Prisma's client reference gives for a level that raises an event rather than printing. src/index.ts imports it instead of constructing its own, and prisma/seed.ts is left with its own client, since a seed runs once and its queries are not the ones anyone is measuring. On the exported client the agent registers prisma.$on("query", handler), where the event carries query, params, duration in milliseconds from when the client issued the query to when the database answered, target and timestamp.

The handler is a small function with its threshold read from SLOW_QUERY_MS in the environment and a default that the pull request states and .env.example documents; a query at or over it is written to stderr as one JSON line with duration, target, query and timestamp, in the same shape whether it is read by a person or a log pipeline. params is left out unless LOG_QUERY_PARAMS=true, because the /signup route puts email addresses through the client and a slow-query log that prints them is a data leak in disguise. A second environment variable, LOG_ALL_QUERIES=true, logs every query with its duration for a debugging session, and is off by default so the handler costs one comparison per query in normal use. The threshold and the two switches are parsed once at startup, not per event.

To see it work the agent starts PostgreSQL in its sandbox, runs prisma migrate dev and the seed, sets SLOW_QUERY_MS=0 so every query qualifies, starts the server with npm run dev, and calls GET /feed?searchString=Prisma and GET /users. The log lines it reads back show the SELECT statements Prisma generated for the contains filter and the relation include, and they go into the pull request as the example of what the log looks like. It also writes a vitest test for the handler itself that feeds it a fake event above and below the threshold and asserts what is written, so the threshold logic is checked without a database.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add slow query logging to this Prisma app. Read package.json, prisma/schema.prisma, prisma.config.ts, src/index.ts and prisma/seed.ts first. Move the adapter and PrismaClient construction into src/prisma.ts, exported once and imported by src/index.ts, with log set so query events are emitted as events and warn and error go to stdout. Register a $on query handler that reads a threshold in milliseconds from SLOW_QUERY_MS, writes each query at or over it to stderr as one JSON line with duration, target, query and timestamp, includes params only when LOG_QUERY_PARAMS is true, and logs every query when LOG_ALL_QUERIES is true. Parse the settings once at startup. Add the variables to .env.example. Start PostgreSQL in the sandbox, migrate and seed, run the server with SLOW_QUERY_MS=0, call the feed and users routes, and put the resulting log lines in the pull request. Write a vitest test for the handler with fake events above and below the threshold. Do not change the schema or the seed.",
  "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/prisma.ts and a test for the handler, changes src/index.ts to import the shared client, and adds SLOW_QUERY_MS, LOG_QUERY_PARAMS and LOG_ALL_QUERIES to .env.example with one comment each. Its description shows the JSON lines the sandbox server wrote for the feed search and the users list with the threshold at zero, the default threshold the handler uses when the variable is unset, and the test output.

Nothing changes in what the routes return, and the schema and migrations are untouched. The description points out that the slowest statement in the sample is the contains filter on title and content in /feed, which is what the log exists to surface, and that an index or a full-text search on those columns is a separate change.

Before merging, a reviewer sets the production threshold, decides whether the seed script should share the client so its queries are also measured, and decides where stderr goes in production so the JSON lines land in the log system the team already reads.

Run it on every Prisma service

A team with several Prisma services sends this body once per repository from its own server, each a 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 client construction: a Next.js app with the client in lib/prisma.ts and a global for hot reload gets the handler there, a service that already has a logger such as pino gets the line written through it, and one on MongoDB, where the event carries no duration, gets a note instead of a handler that would never fire.

Once the log exists, the next step is reading it. An automation on the Project with a schedule trigger set to Monday morning and the prompt "fetch the slow query lines from the last week from the log system the prompt names, group them by target and query shape, and report the three slowest with the route that issues each" produces a report rather than a pull request. The automation's own max_runs_per_hour cap applies to it.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

Prisma's query events are a few lines to subscribe to and a few decisions to get right: where the client is built, what the threshold is, whether parameters are safe to print, and what shape a log pipeline can parse. The agent reads the app's client construction and routes, writes the handler once, and runs real requests against a database in its own sandbox so the pull request shows what the log looks like rather than describing it.

The sample log lines and the test output stay with the run and are pasted into the pull request, so the review is of output the app produced. Several services get the same handler at once, each attached where that service builds its client.

Frequently asked questions

Does it slow down every query?

Each query event costs the handler one comparison against the threshold, and a line is written only when a query crosses it. LOG_ALL_QUERIES prints every query and is meant for a debugging session, not for production.

Will it print email addresses?

Not unless you ask it to. params is left out of the line by default because routes such as /signup pass emails through the client; set LOG_QUERY_PARAMS=true when you need the bound values and your log system is a safe place for them.

Why move the client into its own module?

Because the log option and the $on listener belong on the constructor, and an app that constructs PrismaClient in two files would need both wired. One exported client is also what Prisma's own guidance for long-running servers recommends, so the move is small and in the right direction.

Does this work with the driver adapter?

The example builds the client with @prisma/adapter-pg, and the agent runs the server that way in the sandbox and reads the events back. The query event's duration is measured by the client, so it covers the adapter's round trip to PostgreSQL.

More Prisma jobs

The same job on other stacks

Keep reading