# Add Request ID Logging to a Rocket App

Yes. An agent adds a Rocket fairing that assigns or echoes an X-Request-Id, stores it in request-local state, logs each response with it, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-request-id-logging/rocket/). 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 app is assembled. In a service laid out like TatriX/realworld-rust-rocket, `Cargo.toml` pins `rocket` 0.5.0-rc.1 with only the `json` feature, `rocket_cors` 0.6.0-alpha1, `rocket_sync_db_pools` 0.1.0-rc.1 with `diesel_postgres_pool`, `diesel` 1.4.8, `jsonwebtoken` 7.2.0 and `validator` 0.14, and `rust-toolchain` selects nightly because `lib.rs` opens with `#![feature(proc_macro_hygiene, decl_macro)]`. The `rocket()` function in `lib.rs` mounts nineteen routes under `/api`, attaches the `Db` fairing, a `rocket_cors` fairing and an `AdHoc::on_ignite` from `config.rs` that manages the JWT secret, and registers a JSON 404 catcher. `auth.rs` implements `FromRequest for Auth` under `#[rocket::async_trait]` and prints token decode failures with `eprintln!`. `Cargo.lock` already resolves `log` 0.4.14 and `yansi` through Rocket, and no `uuid` crate. Tests in `tests/` share one `rocket::local::blocking::Client` through `once_cell` in `common.rs`, and `.travis.yml` runs `diesel migration run` and `cargo test` against a Postgres service.

A fairing is Rocket's hook for every request and response. The agent adds `src/request_id.rs` with a `RequestId(String)` newtype and a `RequestIdFairing` whose `info()` returns `Kind::Request | Kind::Response`. `on_request` reads an incoming `X-Request-Id` header, generates a v4 UUID when there is none, and stores it with `req.local_cache(|| RequestId(id))`; `on_response` reads the same cache entry and sets `X-Request-Id` on the response, then logs the method, path, status and id with `log::info!`. Rocket rc.1 installs its own `log` implementation at launch, so that line appears in the same stream and format as Rocket's own request lines. The private newtype matters: `local_cache` is keyed by type, and a bare `String` would collide with any other fairing caching one. `Cargo.toml` gains `uuid` with the `v4` feature and `log` 0.4 as direct dependencies.

Routes get the id through a request guard, `impl<'r> FromRequest<'r> for &'r RequestId`, which returns the cached value and never fails, so a handler such as `delete_article` in `routes/articles.rs` can take `id: &RequestId` and include it when it logs a refusal. The `eprintln!` in `auth.rs` becomes a `log::warn!` that carries the id, read from the request the guard already holds, so a failed token decode can be matched to the client's request. `lib.rs` attaches the fairing before the CORS and database fairings, because fairings run `on_request` in attach order and the id should exist before anything else logs.

Tests reuse `common::test_client()`. `tests/request_id.rs` sends `GET /api/tags` and asserts the response carries an `X-Request-Id` that parses as a UUID; sends the same request with `X-Request-Id: trace-123` and asserts the header comes back unchanged; and requests an unknown path to show the 404 catcher's response carries one too, since fairings run for catcher responses as well. The agent runs `cargo test` on nightly against a Postgres it starts in the sandbox with `init.sql` and `diesel migration run`, the same steps `.travis.yml` takes, and `cargo clippy` on the new module.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add request id logging to this Rocket 0.5.0-rc.1 service. Read Cargo.toml, Cargo.lock, rust-toolchain, src/lib.rs, src/main.rs, src/config.rs, src/auth.rs, src/errors.rs, src/routes/articles.rs, tests/common.rs, tests/tags.rs, .env and .travis.yml first. Write src/request_id.rs with a RequestId newtype, a fairing of Kind::Request | Kind::Response that reuses an incoming X-Request-Id header or generates a v4 UUID, stores it with req.local_cache, sets it on every response and logs method, path, status and id with log::info!, and a FromRequest guard for &RequestId. Attach the fairing first in lib.rs. Replace the eprintln! in auth.rs with log::warn! that includes the id. Add uuid with the v4 feature and log as dependencies. Write tests/request_id.rs using common::test_client covering a generated id, an echoed id and the 404 catcher. Start Postgres with init.sql and diesel migration run, run cargo test and cargo clippy, and open a pull request that quotes the 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

The pull request adds `src/request_id.rs` and `tests/request_id.rs`, changes `src/lib.rs` (the module and the attach), `src/auth.rs` (the warning with the id), `Cargo.toml` and `Cargo.lock` (`uuid` and `log`), and the README (the header name and a sample log line). Its description quotes the `cargo test` summary and two log lines, one with a generated id and one with an id a client sent.

A reviewer checks the fairing's attach order in `lib.rs`, that the newtype is private to the module so nothing else can cache the same type, and that an incoming id is used as sent, since a proxy that already assigns ids expects its own back. They decide whether an incoming value should be length-limited before it is logged.

No route changes its response body. The only visible difference to a client is the new response header.

## Run it on every Linear issue labelled observability

An automation on the Project with a `linear` trigger on `linear.issue.labeled` and the label `observability` starts one read-only run per issue, which reads `lib.rs` and the fairings already attached and comments on the issue with where the id would be read and which handlers log without it. The trigger adds the issue after the prompt and fills in no placeholder.

The pull request is started from the team's own server with this body, the repository in `resources`, the issue URL as a second resource, and a `request_id` that is a UUID v5 of the Linear issue id, so a redelivered webhook returns the run already started instead of opening a second branch.

## Why run it on Rush?

A Rocket change on nightly with a Postgres pool is slow to prove on a laptop: the toolchain, the database, the migrations. The agent does all of it in its own sandbox, runs the suite there, and keeps the test and log output with the pull request, so the reviewer reads a passing run rather than setting one up.

The fairing is written against this crate's pinned release candidate and its existing `local_cache` and guard patterns, not against the latest Rocket docs. A team with several Rocket services starts the same request on each at once and gets one pull request per service, each attached in that service's own `rocket()` builder.

## Frequently asked questions

### Does this need a Rocket upgrade?

No. `Fairing` with `on_request` and `on_response`, `Request::local_cache` and `#[rocket::async_trait]` all exist in 0.5.0-rc.1, which is what `Cargo.lock` resolves. The pull request adds `uuid` and `log` and moves nothing else.

### Why a newtype instead of caching a String?

`local_cache` stores one value per type. If two fairings each cached a `String`, the second would read the first's value. A private `RequestId` type can only be read by code that names it.

### Is a client-supplied id trusted?

It is echoed and logged as sent, which is what a load balancer or gateway that assigns ids expects. The pull request flags that an untrusted client can send any string and suggests a length cap, left for the team to decide.

### Where do the log lines go?

Through the `log` facade that Rocket itself initialises, so they appear with Rocket's own launch and request lines on stdout, at the level Rocket's config allows. No separate logger is added.

### Can a handler read the id?

Yes, by taking `&RequestId` as a guard argument. The guard reads the cached value the fairing stored and never fails, so adding it to a route changes nothing about the route's other outcomes.

## More Rocket jobs

- [Add Structured Logging to a Rocket API](https://getrush.ai/run/add-structured-logging/rocket/)
- [Fix Rocket Errors from Sentry Alerts](https://getrush.ai/run/fix-sentry-errors/rocket/)
- [Review Pull Requests on a Rocket Server](https://getrush.ai/run/review-pull-requests/rocket/)

## The same job on other stacks

- [Add Request ID Logging to a Serverless Express API](https://getrush.ai/run/add-request-id-logging/serverless/)
- [Add Request ID Logging to a Slim App](https://getrush.ai/run/add-request-id-logging/slim/)
- [Add Request ID Logging to a Symfony App](https://getrush.ai/run/add-request-id-logging/symfony/)

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