# Add Structured Logging to a Serverless Framework API from a Linear Issue

Yes. Label the Linear issue and an agent replaces console.log in your Lambda handlers with a JSON logger carrying the request id and route, tests it, and opens a PR.

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

## What the agent does

The agent reads the issue, then the service. In an API shaped like serverless/examples' aws-node-express-dynamodb-api, serverless.yml declares `frameworkVersion: "4"`, a stage parameter `tableName: "users-table-${sls:stage}"`, an AWS provider on `nodejs24.x` and `arm64`, an IAM statement allowing six DynamoDB actions on the `UsersTable` resource, a `USERS_TABLE` environment variable, one function `api` whose handler is `handler.handler` on an `httpApi: "*"` event, and a PAY_PER_REQUEST table. package.json has four dependencies, the two DynamoDB SDK v3 packages, express 5 and serverless-http 4, and no dev dependencies, no scripts and no tests. handler.js builds an Express app with a JSON body parser, `GET /users/:userId` doing a GetCommand, `POST /users` doing a PutCommand, a 404 fallback, and exports `serverless(app)`.

Logging today is two calls: `console.log(error)` in the GET catch block and `console.error(error)` in the POST catch block. Nothing logs a successful request, nothing carries the Lambda request id, and a failed GetCommand prints a stack with no user id beside it. The agent also notices, while reading `POST /users`, that the two validation branches send a 400 without returning, so an invalid body still reaches the PutCommand; it does not widen the issue to fix that, but it logs it as a finding in the pull request, because structured logs will surface it the first time it happens.

The change uses the Powertools for AWS Lambda logger, which prints one JSON object per line with `level`, `message`, `service`, `timestamp` and whatever fields are attached, and reads its service name and level from `POWERTOOLS_SERVICE_NAME` and `POWERTOOLS_LOG_LEVEL`, which the agent adds to `provider.environment` beside `USERS_TABLE`. serverless-http's `request` option gives the Express request the Lambda event and context, so a small middleware creates a child logger per request with the `awsRequestId`, method and path, stores it on `req.log`, and writes one access line on response finish with the status code. The two catch blocks become `req.log.error("...", { err: error, userId })` with the identifier that was being looked up, and the 404 fallback logs at warn with the path. `logger.addContext` carries the function's cold start flag and memory into every line.

To test without AWS, the agent exports the Express app alongside the handler, adds a `test` script using Node's built-in runner, and writes test/logging.test.js that starts the app on an ephemeral port, calls the 404 route and the validation path, which never reach DynamoDB, captures stdout, and asserts each line parses as JSON with the service name, the level and the path. It runs `npm install` and `npm test` in the sandbox and keeps the output. The README gains a Logging section showing one example line and the CloudWatch Logs Insights filter `filter level = "ERROR"` that the JSON shape makes possible.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "A Linear issue labelled agent asks for structured logging in this Serverless Framework service. Read serverless.yml, package.json, handler.js and README.md first and list every console.log or console.error call, what each logs, and what context is missing from it such as the request id or the record key. Add the Powertools for AWS Lambda logger as a dependency, set POWERTOOLS_SERVICE_NAME and POWERTOOLS_LOG_LEVEL in the provider environment, and use serverless-http's request option to pass the Lambda event and context into Express. Add a middleware that creates a per-request child logger with the AWS request id, method and path, attaches it to the request, and writes one access log line with the status on finish. Replace every console call with the request logger, attaching the error and the identifier involved, and log the 404 fallback at warn. Export the Express app, add a test script on Node's built-in test runner, and write a test that exercises routes which do not reach DynamoDB, captures stdout and asserts each line is JSON with the expected fields. Run npm install and npm test. Add a Logging section to the README with one example line and a Logs Insights filter. Do not fix unrelated bugs, but report any you find. Open a pull request that links the issue, lists each log site before and after, and quotes the test output.",
  "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 on its own branch that changes handler.js, package.json and serverless.yml, adds test/logging.test.js and a package-lock.json from the install, and adds a Logging section to README.md. serverless.yml changes only in `provider.environment`; the function, the IAM statement and the table are untouched.

The description links the Linear issue, shows a before-and-after table of the three log sites with the fields each line now carries, quotes `npm test` from the sandbox with the JSON lines it captured, and shows one real access-log line. It reports the finding that the validation branches in `POST /users` fall through to the PutCommand, with the two lines involved, as a separate item for a follow-up rather than a change in this pull request.

Before merging, a reviewer checks that no log line includes the request body, since `POST /users` carries user data, confirms the log level per stage is what they want in `provider.environment`, and deploys to a dev stage to see the lines in CloudWatch. Adding a correlation id from an upstream header or sampling debug logs is a follow-up on the same session.

## Run it on every Linear issue labelled agent

Sign in to Linear once with `POST /me/connections {"type": "app", "name": "linear"}` and finish the authorize URL in the console. Then add an automation to the Project with this prompt and a `linear` trigger on the label you triage with. The trigger adds the issue after the prompt, so a requested field name or log level comes from the issue text; the automation's `max_runs_per_hour` caps how many issues it picks up.

Each labelled issue runs in its own sandbox and opens its own pull request. Once the logger is in, a later issue such as `log the DynamoDB latency on every call` runs against the same handler and extends the child logger rather than starting over, and the test captures the new field.

## Why run it on Rush?

Structured logging is judged on the first bad night, when someone filters CloudWatch by request id and either finds the whole story or finds `console.log(error)`. The only way to know the lines are right before then is to capture them in a test, and that needs the app started outside Lambda with the request hook in place. The agent writes that test and runs it in its own sandbox, so the pull request shows the lines rather than describing them.

The run's record carries the review. The transcript shows every console call the agent found, the hook it used to reach the Lambda context from Express, the JSON lines the test captured, and the validation fall-through it noticed and left for a follow-up. A reviewer who wants the body redacted or a different field name says so in a follow-up and the parked sandbox makes the change with the test still watching.

## Frequently asked questions

### Why Powertools rather than pino or a hand-written JSON logger?

Powertools is built for Lambda: it reads its service name and level from environment variables set in serverless.yml, adds the cold start flag and function memory from the context, and prints one JSON object per line that CloudWatch Logs Insights parses without a filter pattern. A hand-written logger would need the same fields written by hand.

### How does an Express route get the Lambda request id?

serverless-http accepts a request option that runs with the Express request, the Lambda event and the context, so the middleware reads awsRequestId from the context and puts a child logger with it on the request. Every log call in a route then carries the id without passing it around.

### Can this be tested without deploying?

Yes. The Express app is exported alongside the handler, so a test starts it on a local port, hits routes that never reach DynamoDB, captures stdout and asserts each line is JSON with the expected fields. Deployment and CloudWatch are the reviewer's step.

### Will the request body end up in the logs?

No. The access line carries method, path, status and request id, and the error lines carry the error and the identifier involved. The pull request says so explicitly because POST /users carries user data, and the reviewer can tighten it further.

### What is the validation bug the run reports?

In POST /users the two type checks call res.status(400).json without returning, so an invalid body still reaches the PutCommand. The run reports the lines and leaves the fix for a separate change, since the issue asked for logging.

## More Serverless Framework jobs

- [Add X-Ray Tracing to a Serverless Framework API from a Linear Issue](https://getrush.ai/run/add-xray-tracing/serverless/)
- [Investigate Lambda Timeouts in a Serverless Service](https://getrush.ai/run/investigate-lambda-timeouts/serverless/)
- [Reduce Cold Starts for a NestJS API on Serverless Framework](https://getrush.ai/run/reduce-cold-starts/serverless/)

## The same job on other stacks

- [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/)
- [Add Structured Logging to a Socket.IO Server](https://getrush.ai/run/add-structured-logging/socket-io/)

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