# Add Structured Logging to a Hono Worker

Yes. An agent makes your Hono Worker log one JSON object per request and per error, turns on Workers Logs in wrangler.toml, adds Vitest cases and opens a PR.

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

## What the agent does

The agent reads the Worker as it is. In a service shaped like the `basic` workspace of honojs/examples, `package.json` pins `hono ^4.2.4`, `vitest ^1.5.0`, `wrangler ^3.53.0` and `@cloudflare/workers-types`, with `npm run dev` running `wrangler dev src/index.ts` and `npm test` running `vitest --run` under `vitest.config.ts` with `globals: true`; `tsconfig.json` is `strict` with the `vitest/globals` and Workers types. `wrangler.toml` is two lines, a `name` and a `compatibility_date` of 2024-04-01, with no `[observability]` block. In `src/index.ts` the built-in `logger()` import is commented out, a custom middleware on `*` computes `Date.now()` before and after `next()` and sets an `X-Response-Time` header, and `app.onError` does `console.error(`${err}`)` and answers a plain 500. Nothing writes a field a log query could filter on.

Cloudflare's Workers Logs indexes the fields of an object passed to `console.log`, while a string with the value embedded in it is only searchable by text match. So the agent adds `src/log.ts` with one middleware that, after `next()`, calls `console.log` with an object: `method`, `path`, `status`, `durationMs`, `userAgent`, `colo` from `c.req.raw.cf` when present, and a `level`. It replaces the `X-Response-Time` middleware rather than adding a second timer, keeps that header since a test may rely on it, and mounts the middleware on `*` right after `poweredBy()`. `app.onError` becomes a `console.error` with `{ level: 'error', message: err.message, stack: err.stack, method, path }` followed by the same 500 text, so a stack trace is one record instead of a multi-line string.

The Worker only keeps those records if logging is on, so the agent adds `[observability]` with `enabled = true` to `wrangler.toml`, and a `head_sampling_rate` of 1, which is also the default. Workers Logs needs Wrangler 3.78.6 or newer; the `^3.53.0` range allows it, there is no lockfile in the example, and the agent checks `npx wrangler --version` in the sandbox and raises the `devDependencies` floor if the installed one is older. It does not add a logging library: the Workers runtime already turns `console.log` objects into structured records, and a dependency would add bundle size for nothing.

Tests follow `src/index.test.ts`, which calls `app.request('http://localhost/')` and checks status and the `x-powered-by` header with Vitest globals. The new cases use `vi.spyOn(console, 'log')` and `vi.spyOn(console, 'error')`: a `GET /entry/42` logs one object with `method: 'GET'`, `path: '/entry/42'`, `status: 200` and a numeric `durationMs`; a `GET /error` (the route that throws) logs one error object with `message: 'Error has occurred'` and a `stack` string and still answers 500; a `POST /api/posts` logs `status: 201`; and `X-Response-Time` is still present. The agent runs `npm test` and `npx tsc --noEmit` and pastes both, then does one `wrangler dev` request in the sandbox to show the JSON line in the dev output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add structured logging to this Hono Worker and open a pull request. Read package.json, wrangler.toml, tsconfig.json, vitest.config.ts, src/index.ts and src/index.test.ts first. Add src/log.ts with one middleware that, after next(), calls console.log with a single object: level, method, path, status, durationMs, userAgent and colo when c.req.raw.cf is present. Replace the existing X-Response-Time timing middleware with it but keep setting that header. Change app.onError to console.error one object with level, message, stack, method and path, then the same 500 response. Add [observability] enabled = true and head_sampling_rate = 1 to wrangler.toml; check npx wrangler --version is at least 3.78.6 and raise the devDependency floor if not. Do not add a logging library. Add Vitest cases that spy on console.log and console.error: GET /entry/42 logs one object with method, path, status 200 and a numeric durationMs; GET /error logs one error object with message and stack and still answers 500; POST /api/posts logs status 201; X-Response-Time is still set. Run npm test and npx tsc --noEmit and paste the output. Do not change routes, the basicAuth credentials or the compatibility_date.",
  "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 with a new `src/log.ts`, a few changed lines in `src/index.ts` where the timing middleware and `onError` were, an `[observability]` block in `wrangler.toml`, possibly a bumped `wrangler` floor in `package.json`, and four new cases in `src/index.test.ts`. The description shows one logged object from a test run, the `vitest --run` and `tsc --noEmit` output, and the Wrangler version the sandbox installed.

The example repository has no workflow, only `.github/dependabot.yml`, so the pasted output is the check. On a Worker with a Vitest workflow the same cases run on the pull request.

A reviewer checks that no request body, `Authorization` header or cookie is logged, that the error record carries `stack` but the response still says only `Custom Error Message`, that `head_sampling_rate` matches the plan's log budget, and that the field names are the ones the team's log queries will use. After merge, `wrangler deploy` turns the setting on; logs are then readable in the dashboard and `wrangler tail`.

## Run it on every new Worker

A team with many Workers sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `wrangler.toml` and `src/index.ts`, so a Worker that already uses `hono/logger` gets its text lines replaced by the same object shape, and each opens its own pull request with the same field names across services. A `request_id` in each body makes a retry safe.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends with the `session_url`, so a script can collect the pull requests and check that every Worker now logs the same fields.

## Why run it on Rush?

Logging is the change nobody tests: a string template is written, deployed, and the first time someone needs to filter by status code they find they cannot. In a Rush sandbox the agent sends requests through `app.request`, asserts the exact object that reaches `console.log`, runs a real `wrangler dev` and keeps that output in the run's record beside the diff, so the reviewer sees a logged record rather than a promise of one.

It is also a small change that touches a dozen Workers in the same way. One request per repository gives each its own sandbox and pull request with identical field names, and the Vitest and TypeScript runs that prove them, in the time one laptop pass on one Worker would take.

## Frequently asked questions

### Why not pino or another logging library?

On Workers, `console.log` with an object already becomes a structured record that Workers Logs indexes by field, so a library would add bundle size and a second abstraction for nothing. The agent keeps a single small middleware in `src/log.ts` instead.

### Does it replace hono/logger?

The `basic` example has it commented out, so there is nothing to replace. On a Worker that uses `logger()`, the agent removes it, because it prints text lines that would duplicate the JSON records and cannot be filtered by field.

### What does the observability block do?

`[observability] enabled = true` makes the deployed Worker send its `console` output to Workers Logs, where the object fields are indexed; without it the records are only visible in `wrangler tail`. `head_sampling_rate` sets the share of requests kept, 1 meaning all, and needs Wrangler 3.78.6 or newer.

### Will it log request bodies or headers?

No. The object carries method, path, status, duration, user agent and colo. `Authorization`, cookies and bodies are left out on purpose, and the error record carries the stack but not the request body.

## More Hono jobs

- [Dockerize a Hono App Running on Bun](https://getrush.ai/run/dockerize-app/hono/)
- [Fix Errors in a Hono Deployment](https://getrush.ai/run/fix-cloudflare-worker-errors/hono/)
- [Fix N+1 KV Reads in a Hono API](https://getrush.ai/run/fix-n-plus-one-queries/hono/)

## The same job on other stacks

- [Add Structured Logging to a Koa API](https://getrush.ai/run/add-structured-logging/koa/)
- [Add Structured JSON Logging to a Ktor Server](https://getrush.ai/run/add-structured-logging/ktor/)
- [Add Structured Logging to a Leptos Axum App](https://getrush.ai/run/add-structured-logging/leptos/)

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