# Add Prometheus Metrics to an Echo API

Yes. An agent adds a request counter and latency histogram as Echo middleware, serves /metrics with client_golang, tests the scrape with httptest and opens a PR.

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

## What the agent does

The agent reads how the Echo instance is built before deciding where a metrics middleware belongs. In a project like xesina/golang-echo-realworld-example-app, `router/router.go` creates the instance with `e.Pre(middleware.RemoveTrailingSlash())`, `middleware.Logger()`, a permissive CORS config and a go-playground validator; `main.go` mounts `echo-swagger` on `/swagger/*`, opens a SQLite database through the old `jinzhu/gorm` in `db/db.go`, auto-migrates the models, registers every handler on the `/api` group and listens on `127.0.0.1:8585`. `handler/routes.go` registers `/users`, `/user`, `/profiles/:username`, `/articles` with its `:slug` and `/comments/:id` children, and `/tags`, with a JWT middleware of the project's own in `router/middleware/jwt.go`. `go.mod` says `go 1.18`, Echo v4.1.16 and `dgrijalva/jwt-go`; `Makefile` runs `go test -v -race ./...` and `go build -race`; `.github/workflows/go.yml` sets up Go 1.18 and runs `go build -v ./...` and `go test -v ./...` on push and pull request; `handler/handler_test.go` builds its own `router.New()` and a test database under `TestMain`.

`echo-contrib`'s `echoprometheus` package is marked deprecated and its current source targets Echo v5, so the agent does not take that road for a v4 app. It adds `github.com/prometheus/client_golang` and writes `router/middleware/metrics.go`: a `prometheus.NewRegistry()`, a `CounterVec` `http_requests_total` and a `HistogramVec` `http_request_duration_seconds`, both labelled with the method, the route pattern and the status. The route label comes from `c.Path()`, the pattern Echo matched, so `/api/articles/:slug` is one series however many slugs are requested, and a request that matched no route is labelled as such rather than by its raw URL. The middleware is added in `router.New()` after the logger, with a skipper for `/metrics` and `/swagger/*`, and `main.go` serves `/metrics` through `echo.WrapHandler(promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))` on the same listener.

Dependencies are handled honestly rather than silently. `client_golang`'s current source declares a newer Go than the module's `go 1.18` directive, so the agent runs `go get` with the sandbox's toolchain, lets Go pick a compatible release, raises the `go` directive in `go.mod` only if the download requires it, runs `go mod tidy`, and writes in the pull request which version was chosen and whether the directive moved. The CI workflow's `go-version: 1.18` is updated in the same change if the directive moved, since otherwise the build would fail on the first push.

Tests go next to the middleware in `router/middleware/metrics_test.go`: build an `echo.New()` with the middleware and one `GET /ping` route, send two requests through `httptest`, scrape `/metrics` and assert the line `http_requests_total{method="GET",path="/ping",status="200"} 2` with `prometheus/testutil`, then send a request to an unregistered path and check it lands under its own status label. Because the handler tests use their own `router.New()`, the middleware is exercised there too. The agent runs `go vet ./...`, `go build -race` and `go test -v -race ./...`, which needs `gcc` for the SQLite driver, starts the binary once and scrapes `/metrics` with curl after a few requests.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Prometheus metrics to this Echo API. Read go.mod, main.go, router/router.go, router/middleware/jwt.go, handler/routes.go, handler/handler_test.go, Makefile and .github/workflows/go.yml first. Do not use echo-contrib's echoprometheus, which is deprecated and targets Echo v5; add github.com/prometheus/client_golang and write router/middleware/metrics.go with a dedicated registry, an http_requests_total counter and an http_request_duration_seconds histogram labelled by method, matched route pattern from c.Path() and status, with a skipper for /metrics and /swagger. Register it in router.New after the logger and serve /metrics in main.go through echo.WrapHandler and promhttp.HandlerFor on the same listener. Let go get choose a client_golang release the toolchain supports, raise the go directive only if required, run go mod tidy, and update go-version in .github/workflows/go.yml to match if it moved. Write router/middleware/metrics_test.go with httptest asserting the counter after two requests and the label for an unmatched route. Run go vet ./..., go build -race and go test -v -race ./..., start the server once and scrape /metrics with curl, and open a pull request that lists the metric names and labels and the module changes.",
  "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 that adds `router/middleware/metrics.go` and `router/middleware/metrics_test.go`, changes `router/router.go` and `main.go`, and updates `go.mod` and `go.sum`, plus `.github/workflows/go.yml` when the Go directive had to move. The description lists the two metric names with their labels, says which `client_golang` release was resolved and why, and pastes the first lines of a real `/metrics` scrape from the sandbox.

The run's record keeps `go get`, `go mod tidy`, `go vet`, the race build, the full `go test -v -race ./...` output including the existing handler tests, and the curl scrape, so a reviewer sees the metrics endpoint answering and the old tests still passing on the resolved module set.

Before merging, a reviewer decides whether `/metrics` may stay on the application listener, which `main.go` binds to `127.0.0.1:8585`, or should move to a second port, and whether to put it behind the project's JWT middleware; the pull request leaves it open and unauthenticated on purpose and says so.

## Run it on every Go service with no metrics

A team with several Echo services starts one run per repository with one `POST /o/{org}/sessions` each, this prompt as `input` and the repository in `resources`. Each run reads its own `router.New()` and route table, so a service already on a current Echo release skips the module work, and a service that already uses a registry gets its collectors added to that one instead of a second.

Send a `request_id`, a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` receives `run.completed` for each run the key starts, with the final answer in `result`, so a dashboard can collect the metric names from every service.

## Why run it on Rush?

On a repository that still says `go 1.18` and Echo 4.1, the real work is the module resolution: which `client_golang` release Go will accept, whether the directive has to move, and whether the old JWT and gorm dependencies still build afterwards. The agent does that resolution in a sandbox of its own with a C toolchain for the SQLite driver, runs the race build and the whole test suite, and reports the exact outcome rather than a guess.

Every command's output stays with the run, including a scrape of the real endpoint, so the pull request shows the metric names as Prometheus will see them. The same request goes to every Go service in the org at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why not echo-contrib's echoprometheus?

Its source is marked deprecated and its current `go.mod` requires Echo v5, while this app is on v4. A middleware over `client_golang` directly is a few dozen lines, has no Echo version constraint, and gives the same two metrics with the labels the project chooses.

### Will the route label blow up cardinality?

No. The label is `c.Path()`, the registered pattern such as `/api/articles/:slug`, not the request URL, so every slug shares one series. Requests that match no route get a fixed label instead of their raw path.

### Does it change the Go version?

Only if `go get` cannot find a `client_golang` release for the `go 1.18` directive. The agent lets the toolchain resolve it, raises the directive if required, mirrors the change in the CI workflow, and states both in the pull request so the reviewer sees a version bump as a decision, not a side effect.

### Is /metrics protected?

Not by this change. It is served on the same listener as the API, unauthenticated, which is the usual setup when the port is only reachable by the scraper. The pull request names the alternatives: a second listener, or the project's JWT middleware in front of it.

## More Echo jobs

- [Add Rate Limiting to an Echo API](https://getrush.ai/run/add-rate-limiting/echo/)
- [Add Request ID Logging to an Echo App](https://getrush.ai/run/add-request-id-logging/echo/)
- [Add Request Timeouts to an Echo App](https://getrush.ai/run/add-request-timeouts/echo/)

## The same job on other stacks

- [Add Prometheus Metrics to a Fastify App](https://getrush.ai/run/add-prometheus-metrics/fastify/)
- [Add Prometheus Metrics to a Fiber App](https://getrush.ai/run/add-prometheus-metrics/fiber/)
- [Add Prometheus Metrics to a Gin API from a Linear Issue](https://getrush.ai/run/add-prometheus-metrics/gin/)

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