# Add Structured Logging to a Gin API from a Linear Issue

Yes. An agent takes a labelled Linear issue, replaces Gin's plain-text logger with slog JSON output and a request-log middleware, and opens a tested PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-structured-logging/gin/). 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 reads how the API logs today. In an API shaped like gothinkster/golang-gin-realworld-example-app, `go.mod` sets `go 1.21`, so `log/slog` is in the standard library, and pins `gin` 1.10.0, `gorm.io/gorm` 1.25.12 with the sqlite driver, `golang-jwt/jwt/v5` and `testify`. `hello.go` builds the router with `gin.Default()`, which installs Gin's plain-text `Logger` and `Recovery`, registers the `/api` groups behind `users.AuthMiddleware` and reads `PORT` from the environment; it reports a failed `db.DB()` with `log.Println` and a failed `Run` with `log.Fatal`. `common/database.go` prints every open or directory error with `fmt.Println`, and `common/utils.go` prints a token-signing failure with `fmt.Printf`. Nothing emits a key-value line a log collector can parse.

The agent adds `common/logger.go` with a `NewLogger` that returns an `slog.Logger` on a JSON handler writing to stdout, its level read from a `LOG_LEVEL` variable with `info` as the default, and a `RequestLogger(*slog.Logger) gin.HandlerFunc` middleware that records, after `c.Next()`, the method, path, status, latency, client IP and, when `AuthMiddleware` has set it, the `my_user_id` value from the context, with `c.Errors` attached as an error attribute. In `hello.go` it swaps `gin.Default()` for `gin.New()` with `gin.Recovery()` and the new middleware, replaces `log.Println` and `log.Fatal` with `logger.Error` followed by `os.Exit(1)` where the program cannot continue, and turns the `fmt.Println` calls in `common/database.go` and `common/utils.go` into `slog.Error` calls with the error as an attribute. GORM's own logger and the `logger.Default.LogMode(logger.Info)` in `TestDBInit` stay as they are.

The tests follow the packages' existing style. `common/logger_test.go` builds a logger on a `bytes.Buffer`, runs one request through a `gin.New()` router with the middleware the way `users/unit_test.go` builds its routers, decodes the line with `encoding/json` and asserts the `method`, `path`, `status` and `user_id` keys with testify. A second case checks that `LOG_LEVEL=debug` lowers the level and that an unknown value falls back to `info`. The router built with `gin.Default()` in `common/unit_test.go` is left alone, since it tests something else.

Before pushing, the agent runs what `.github/workflows/ci.yml` runs: `scripts/gofmt.sh`, `scripts/coverage.sh` (which runs `go test` per package with the atomic cover mode), `golangci-lint` at the v1.61 the workflow pins, `gosec`, and `scripts/run-api-tests.sh`, which builds `hello.go`, waits for `/api/ping` and runs the Conduit Postman collection with Newman. It pastes the new JSON lines from that server run into the pull request and adds `LOG_LEVEL` to `readme.md`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "A Linear issue labelled agent says: \"Switch the API to structured JSON logs so the log collector can index them. Every request should produce one line with method, path, status, latency and the user id when known, and startup and database errors should be logged the same way.\" Do the work in this repository. Read go.mod, hello.go, common/database.go, common/utils.go, users/middlewares.go, users/unit_test.go, scripts/coverage.sh, scripts/run-api-tests.sh and .github/workflows/ci.yml first. Use log/slog from the standard library; add no logging dependency. Add common/logger.go with a NewLogger that writes JSON to stdout at a level read from LOG_LEVEL (default info) and a RequestLogger gin middleware that logs method, path, status, latency, client IP, the my_user_id context value when set, and any c.Errors. In hello.go use gin.New with gin.Recovery and that middleware instead of gin.Default, and replace log.Println and log.Fatal with the logger. Replace the fmt.Println and fmt.Printf error output in common/database.go and common/utils.go with slog calls carrying the error as an attribute. Leave GORM's logger alone. Add common/logger_test.go that captures a request's log line in a buffer, decodes it and asserts the keys, and tests the LOG_LEVEL parsing. Run scripts/gofmt.sh, scripts/coverage.sh, golangci-lint, gosec and scripts/run-api-tests.sh, paste the results and a few JSON log lines in the pull request description, and document LOG_LEVEL in readme.md. Do not change any route, model or serializer.",
  "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 the new `common/logger.go` and `common/logger_test.go`, the middleware and logger wiring in `hello.go`, the replaced error output in `common/database.go` and `common/utils.go`, and a `LOG_LEVEL` entry in `readme.md`. `go.mod` and `go.sum` do not change, because `log/slog` ships with Go 1.21. The description shows the gofmt, coverage, lint and security results and the JSON lines the server printed while Newman ran the Conduit collection against it.

The repository's `CI` workflow runs on the pull request: the `Test` job across Go 1.21, 1.22 and 1.23, the `Lint` job, the `Security Scan` job and the `API Integration Test` job, so the new test and the live request logs are checked on every supported Go version.

A reviewer checks that the middleware logs after `c.Next()` so the status is the final one, that the user id attribute appears only when `AuthMiddleware` set it, that no token or password reaches a log line, and that `gin.Recovery()` still sits in front of the handlers. Then they point the collector at stdout.

## Run it on every Linear issue labelled agent

In the Project that holds the API, add an automation with this prompt and a `linear` trigger on `linear.issue.labeled` filtered to the `agent` label. Each labelled issue starts its own run in its own sandbox and ends in its own pull request; the issue's text follows the prompt as data, so an issue that also asks for a request id or a different log level makes its own change.

Changes made by an app integration never fire the trigger, so the agent's own comments and status updates on the issue start no further runs, and the automation's `max_runs_per_hour` caps how many issues become runs at once.

## Why run it on Rush?

A logging change touches every request path and every error branch, so the only convincing check is a real server handling real traffic. In a Rush sandbox the agent builds the binary, runs the Conduit Postman collection against it the way the CI script does, and reads the JSON lines it printed; those commands and their output stay in the run's transcript, so the pull request shows what the collector will receive rather than a description of it.

The result passes the repository's own gates, gofmt, the per-package coverage run, golangci-lint, gosec and the API integration test, before a reviewer opens it. The same automation handles every logging issue the team labels, one sandbox and one pull request each.

## Frequently asked questions

### Why slog and not zap or zerolog?

Because `go.mod` already requires Go 1.21, which ships `log/slog`, so the change adds no dependency and no new API for the team to learn. A JSON handler on stdout is what most collectors read; switching handlers later is one line in `common/logger.go`.

### Does the user id come from the JWT on every request?

Only on routes behind `users.AuthMiddleware`, which sets `my_user_id` on the context after verifying the token. The middleware reads that value after the handler runs and adds it as an attribute when it is non-zero, so anonymous requests log without it.

### What about GORM's query logging?

It is unchanged. `common/database.go` opens the main database with the default GORM config and the test database with `logger.Info` mode, and the issue asks about request and error logs, not SQL. Routing GORM's logger through slog would be a separate, scoped change.

### Will the Postman API tests still pass?

Yes. The middleware only observes the request and response; routes, status codes and bodies are untouched. The agent runs `scripts/run-api-tests.sh`, which builds the server and runs the Conduit collection with Newman, and includes the summary in the pull request.

## More Gin jobs

- [Inventory the API Endpoints of a Gin Service](https://getrush.ai/run/api-endpoint-inventory/gin/)
- [Dockerize a Gin API](https://getrush.ai/run/dockerize-app/gin/)
- [Fix a Failing CI Build in a Gin Project](https://getrush.ai/run/fix-failing-ci/gin/)

## The same job on other stacks

- [Add Structured Logging to a Hono Worker](https://getrush.ai/run/add-structured-logging/hono/)
- [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/)

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