What the agent does
The agent reads how requests reach procedures before adding a logger. In an app laid out like trpc/examples-next-prisma-starter, src/pages/api/trpc/[trpc].ts calls createNextApiHandler with the appRouter, createContext and an onError that console.errors only INTERNAL_SERVER_ERROR. src/server/trpc.ts creates the instance with initTRPC.context<Context>().create({ transformer, errorFormatter }) and exports router, publicProcedure, mergeRouters and createCallerFactory; src/server/context.ts has createContextInner returning an empty object and createContext wrapping it for Next. src/server/prisma.ts builds one PrismaClient with log: ['query', 'error', 'warn'] in development and ['error'] otherwise, and src/server/env.ts validates DATABASE_URL and NODE_ENV with zod at build time. package.json runs oxlint for lint, vitest 5 for test-unit and Playwright for test-e2e, and .github/workflows/main.yml runs both jobs against a Postgres service on Node 22.
The logger is pino, added to dependencies, in a new src/server/logger.ts that writes JSON to stdout at a level from LOG_LEVEL, which the agent adds to the zod schema in env.ts as an optional enum defaulting to info. createContextInner gains two fields: requestId, which createContext takes from an incoming x-request-id header or mints with crypto.randomUUID(), and log, a child logger bound to that id. The Context type is inferred from createContextInner, so post.test.ts, which calls createContextInner({}), keeps compiling once the two fields have defaults for tests.
The request line is a tRPC middleware in src/server/trpc.ts: t.middleware records performance.now(), awaits next(), and logs one line with path, type (query or mutation), ok, durationMs and, on failure, the TRPCError code. The agent defines publicProcedure as t.procedure.use(logging) so every existing procedure in src/server/routers/post.ts and the healthcheck in _app.ts is covered without touching them. onError in [trpc].ts switches from console.error to ctx.log.error with the error and the path, and responseMeta sets x-request-id on the response so a client can quote the id back. Prisma's query events stay on Prisma's own logger; the pull request notes how to route them through pino with the event-based log option if the team wants one stream.
Tests go beside post.test.ts in src/server/routers/logging.test.ts. They build a logger with pino writing to an in-memory Writable, pass it to createContextInner with a fixed requestId, call caller.healthcheck() and caller.post.byId({ id: 'missing' }) through createCaller, and parse the captured lines to assert ok: true with a numeric durationMs for the first and ok: false with code: 'NOT_FOUND' and the same requestId for the second. pnpm test-unit runs them with the dotenv/config setup vitest.config.mts names, and pnpm lint and pnpm typecheck run clean, since oxlint is the linter the repository configures in .oxlintrc.json.
Start it with one API call
POST https://api.phoenix.so/o/{org}/sessions with this body:
{
"agent": "claude",
"input": "Add structured logging to this tRPC API. Read src/pages/api/trpc/[trpc].ts, src/server/trpc.ts, src/server/context.ts, src/server/prisma.ts, src/server/env.ts, src/server/routers/_app.ts, post.ts and post.test.ts, vitest.config.mts, package.json and .github/workflows/main.yml first. Add pino and a src/server/logger.ts that writes JSON to stdout at a level from LOG_LEVEL, added to the env schema as an optional enum defaulting to info. Put requestId (from x-request-id or crypto.randomUUID()) and a child logger on the context in createContextInner, with defaults so existing tests compile. Add a t.middleware in trpc.ts that logs path, type, ok, durationMs and the TRPCError code on failure, and make publicProcedure use it. Replace console.error in onError with ctx.log.error and set x-request-id in responseMeta. Write src/server/routers/logging.test.ts using a pino instance that writes to an in-memory stream, asserting the line for a successful healthcheck and for a NOT_FOUND post.byId. Run pnpm lint, pnpm typecheck and pnpm test-unit, and open a pull request with the output and one sample line.",
"resources": [
{
"url": "https://github.com/your-org/your-app"
}
]
}- 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.
- 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.
- 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/server/logger.ts and src/server/routers/logging.test.ts, changes src/server/trpc.ts, src/server/context.ts, src/server/env.ts and src/pages/api/trpc/[trpc].ts, and adds pino to package.json. Its description pastes the lint, typecheck and vitest output and one JSON line from the sandbox so a reviewer sees the field names before choosing a log drain.
Every procedure call now leaves one line with the same keys, so a search for ok:false or for one requestId works in any log store, a slow mutation shows as a durationMs outlier under its path, and an error a user reports can be found from the x-request-id header their browser received. The client-side loggerLink in src/utils/trpc.ts is untouched; it serves the browser console, not the server.
Before merging, a reviewer confirms the LOG_LEVEL default for production, decides whether x-request-id from the internet should be trusted or only the proxy's, and checks that no procedure logs its input, which the middleware deliberately leaves out.
Run it on every API whose errors only reach the console
A team with several tRPC services starts one run per repository from the terminal: one POST /o/{org}/sessions each with that repository in resources and a request_id that is a UUID v5 of its full name, so a retried call returns the run already started. Each run reads its own adapter: an app on the fetch adapter or the App Router gets the request id from Request headers instead of NextApiRequest, an Express host gets the middleware plus pino-http, and one that already has pino gets only the tRPC middleware and the test.
Each run opens its own pull request on its own branch, and GET /o/{org}/sessions lists them newest first, so the person who started the batch reads every test result from one place.
The use case this job follows, with its automation and trigger: Hand off a long task.
Why run it on Rush?
A logging change is judged by its output, and the output only exists when real procedures run. The agent runs them in its sandbox against a Postgres it starts, reads the lines back as JSON in a test, and asserts the keys, so a later refactor that drops requestId or logs an input fails the suite rather than the on-call engineer's search.
The run keeps every command and its output, so the reviewer sees pnpm test-unit pass and the sample line without cloning the branch or installing Node 22, pnpm and Postgres. Several services can be instrumented at once, each in its own sandbox, and one that already logs through pino is left with a note instead of a second logger.
Frequently asked questions
Why a tRPC middleware instead of logging in the Next handler?
The HTTP handler sees one request, which with httpBatchStreamLink may carry several procedure calls in a batch. The middleware runs once per procedure, so each call gets its own line with its own path, outcome and duration, and the request id on the context ties the batch together.
Does the existing post.test.ts still pass?
Yes. createContextInner gives requestId and log defaults when the caller passes nothing, so the test's createContextInner({}) is unchanged and its logs go to a silent logger. The new test passes an explicit logger to capture lines; nothing is mocked.
What happens to Prisma's query logs?
They keep going through Prisma's own output as configured in src/server/prisma.ts. The pull request shows the event-based log option that would forward query events to pino at debug, and leaves the switch to the team because it changes development output volume.
Is pino-pretty used?
Not in code. JSON is the output in every environment so the files and the drain see the same shape; a developer who wants readable output pipes pnpm dev through pino-pretty locally. That keeps the production path free of a transport that forks a worker thread.
Does the middleware log procedure inputs?
No. Inputs can hold a post body or a credential, so the line carries the path and the outcome only. A team that needs an input field adds it per procedure with an explicit allowlist, which the pull request notes as the safe way to extend the line.