All jobs

Add Structured Logging to a Rocket API

Yes. An agent adds a JSON tracing subscriber and a request-logging fairing to a Rocket API, with request id, user id, status and duration, tests it, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the crate before picking a logging stack. In an API laid out like TatriX/realworld-rust-rocket, Cargo.toml takes rocket 0.5.0-rc.1 with default-features = false and the json feature, rocket_cors 0.6.0-alpha1, diesel 1.4.8 with the postgres and chrono features, and builds on the nightly toolchain named in rust-toolchain. Cargo.lock resolves log 0.4.14, which is the facade Rocket's own request lines and launch banner go through, and a search of src/ finds no info! or error! call of the project's own. src/lib.rs builds the instance in rocket(): nineteen routes mounted under /api, the Db fairing from src/database/mod.rs, the CORS fairing, AppState::manage() from src/config.rs, and a 404 catcher. src/auth.rs is a request guard that reads Authorization: Token … into an Auth with the user's id and username.

The subscriber goes in src/lib.rs beside the launch. The agent adds tracing, tracing-subscriber with the json and env-filter features, and tracing-log, whose bridge forwards Rocket's log records into the same subscriber so there is one stream, not two formats. init_logging() builds a JSON formatter writing to stdout with a filter from RUST_LOG, defaulting to info, and is called once at the top of rocket(); Rocket's own log_level is set to critical in config::from_env() so its per-request line does not duplicate the one the fairing writes. In tests the init is guarded with try_init so the shared Client in tests/common.rs can build the instance more than once.

The request line comes from a fairing in a new src/logging.rs. on_request stores an Instant and a request id in request.local_cache(), taking the id from an incoming X-Request-Id header when there is one and minting a UUID otherwise; on_response emits one info! event with method, path, status, duration_ms, request_id and, when the request carried a valid token, user_id by asking for Option<Auth> the way the handlers do, and writes the id back as a response header so a client can quote it. A 5xx is logged at error level and everything else at info, and path is the route's URI, not the query string, so a token in a query never lands in a log.

The test lives in tests/logging.rs and follows the existing files. It builds its own rocket::local::blocking::Client rather than the shared one, installs a JSON subscriber with tracing::subscriber::with_default writing into a Mutex<Vec<u8>>, sends GET /api/tags and GET /api/articles/does-not-exist, and parses each line with serde_json to assert the fields, the 200 and 404 statuses, that duration_ms is a number, and that a supplied X-Request-Id is echoed. cargo test is the check .travis.yml runs after diesel migration run, and the agent runs it the same way against a Postgres it starts in the sandbox from init.sql.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add structured JSON logging to this Rocket API. Read Cargo.toml, Cargo.lock, rust-toolchain, src/lib.rs, src/config.rs, src/auth.rs, src/database/mod.rs, tests/common.rs and .travis.yml first, and keep the Rocket version as it is. Add tracing, tracing-subscriber with the json and env-filter features, and tracing-log; initialise a JSON subscriber to stdout once in rocket() with a RUST_LOG filter defaulting to info, bridge Rocket's log records into it, and set Rocket's log_level to critical in config::from_env() so requests are logged once. Add a fairing in src/logging.rs that records an Instant and a request id (from X-Request-Id or a new UUID) in request.local_cache on request, and on response emits one event with method, path, status, duration_ms, request_id and user_id when an Auth guard succeeds, at error level for 5xx; echo the request id as a response header. Write tests/logging.rs with its own local Client and a subscriber writing to a buffer, assert the JSON fields for a 200 and a 404 and the echoed id. Start Postgres from init.sql, run diesel migration run and cargo test, and open a pull request with the output and a sample log line.",
  "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/logging.rs and tests/logging.rs, changes src/lib.rs and src/config.rs, and updates Cargo.toml and Cargo.lock with the three tracing crates. Its description pastes the cargo test run on nightly and one real line from the sandbox, so a reviewer sees the field names before deciding on a log pipeline.

Every request now produces exactly one JSON line with the same keys, so a query for status >= 500 or for one request_id works in any log store without a parser, and a user's complaint can be matched to the lines that carried their user_id. Rocket's launch banner and its warnings still appear, in the same JSON shape, because the log bridge carries them.

Before merging, a reviewer confirms the RUST_LOG default and whether debug should include Diesel's query logs, decides whether the X-Request-Id header should be trusted from the internet or only from the proxy in front of the API, and checks that no handler writes a request body into a log field.

Run it on every service without one log line per request

A team moving several Rust services to a shared log store starts one run per repository from the terminal: one POST /o/{org}/sessions each with that repository in resources and a request_id that is a UUID v5 of its full name, so a retried call returns the run already started. Each run reads its own crate: a service on Rocket 0.5.0 final uses the same fairing API, one on Axum gets a tower-http trace layer with the same field names, and one that already has a subscriber gets only the fairing and the test.

Each run opens its own pull request on its own branch, and GET /o/{org}/sessions lists them newest first, so the person who started the batch reads every test result from one place.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

Log formats are easy to write and hard to keep consistent: a fairing that works can still log the query string, print the duration as a string, or double every request because Rocket's own line was left on. The agent checks each of those by parsing its own output in a test, with the buffer standing in for the log store, so the shape is asserted on every pull request rather than noticed in a dashboard.

The run keeps every command and its output, so the reviewer sees the nightly build, the migration and the test pass without installing the toolchain and Postgres locally. Several services can be instrumented at once, each in its own sandbox, and one that already emits JSON is left with a note instead of a second subscriber.

Frequently asked questions

Why tracing rather than a JSON logger on the log crate?

The tracing subscriber gives structured fields without string formatting, and tracing-log keeps Rocket's own log records in the same stream. A later change can add spans, for example around the Diesel call inside db.run, without changing the format again. On this version of Rocket the project's own records are the only ones, so the bridge is what makes the output uniform.

Does it log the request body or the token?

No. The fairing records the method, the route path, the status, the duration, the ids and nothing from headers except the request id it echoes. The Authorization header is read only by the existing Auth guard to produce user_id, and the query string is dropped from path so a token passed that way never reaches a log.

Will the shared test client in tests/common.rs break?

The subscriber is installed with try_init, so building the instance a second time in the same process does not panic. The logging test uses its own client and a thread-scoped subscriber, so it does not change what the other test files see.

What about the nightly toolchain?

The crate pins nightly in rust-toolchain and src/lib.rs uses proc_macro_hygiene and decl_macro, so the agent builds and tests on nightly as the repository does. The three crates it adds build on stable too, so a later move off nightly needs no change here.

How does the duration handle slow database calls?

The timer starts in on_request and stops in on_response, so it covers the whole handler including the blocking db.run closure. A route whose p99 jumps shows up as a duration_ms outlier under its path, which is the question the field is there to answer.

More Rocket jobs

The same job on other stacks

Keep reading