# Add Structured Logging to an Axum API

Yes. An agent swaps env_logger for a JSON tracing subscriber, puts a request id in every line through TraceLayer, tests it with cargo test and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-structured-logging/axum/). 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 service logs today before it changes anything. In an API shaped like launchbadge/realworld-axum-sqlx, `Cargo.toml` pins `axum` 0.3.4 with the `tower-log` feature, `tower-http` 0.2 with `trace`, `env_logger` 0.9 and `log` 0.4, and `src/main.rs` calls `env_logger::init()` before it parses `Config` with clap and connects the SQLx pool. `src/http/mod.rs` already wraps the router in `TraceLayer::new_for_http()`, with a comment telling you to set `RUST_LOG=tower_http=debug`, and `.env.sample` ships `RUST_LOG=realworld_axum_sqlx=debug,tower_http=debug`. The application's own lines go through `log::error!` in `src/http/error.rs` for SQLx and generic errors and `log::debug!` in `src/http/extractor.rs` for a bad `Authorization: Token` header. The `Cargo.lock` shows `tracing` 0.1 is already compiled in through tower-http, so the span machinery is there and only the subscriber and the format are missing.

It adds `tracing`, `tracing-subscriber` with the `json` and `env-filter` features, and `tracing-log` so the existing `log::` calls in `error.rs` and `extractor.rs` land in the same output without rewriting them. `main.rs` replaces `env_logger::init()` with a subscriber built from `EnvFilter::from_default_env()`, so `RUST_LOG` keeps working as `.env.sample` documents, and a new `log_format` field on `Config` (clap reads it from `LOG_FORMAT`, default `text`) picks the JSON layer in production and the human-readable layer under `cargo run`. The JSON lines carry `timestamp`, `level`, `target`, `message` and the fields of every open span.

The request id comes from the `TraceLayer` the service already has. The agent gives it a `make_span_with` closure that opens an `info_span!` named `request` with `method`, `uri` and `request_id`, where the id is the incoming `x-request-id` header if a gateway sent one and a `uuid` v4 otherwise, using the `uuid` 0.8 crate already in `Cargo.toml`. To echo the id back, it enables tower-http's `request-id` feature and adds `SetRequestIdLayer` and `PropagateRequestIdLayer` in front of the trace layer, picking the newest release on the 0.2 line that has the feature since the lockfile's 0.2.0 predates it. Every `log::error!` from a handler then prints inside that span, so one `request_id` ties a `500` from `error.rs` to the `POST /api/articles` that caused it.

Tests follow the repository's shape: there is one `#[test]` in `src/http/articles/mod.rs` and the GitHub Actions workflow in `.github/workflows/rust.yml` runs `cargo build --verbose` and `cargo test --verbose` against a Postgres service, then the Realworld Postman collection with `cargo run` in the background. The agent adds unit tests for the id function, one asserting a supplied `x-request-id` is kept and one asserting a missing header yields a UUID, and runs `cargo test`, `cargo fmt --check` and `cargo clippy`. It then starts the server against a Postgres in the sandbox with `LOG_FORMAT=json`, calls `GET /api/tags` with and without the header, and pastes the two JSON lines in the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add structured JSON logging with a request id to this Axum service and open a pull request. Read Cargo.toml, Cargo.lock, .env.sample, src/main.rs, src/config.rs, src/http/mod.rs, src/http/error.rs, src/http/extractor.rs and .github/workflows/rust.yml first. Add tracing, tracing-subscriber with the json and env-filter features, and tracing-log so the existing log::error! and log::debug! calls keep working. Replace env_logger::init() in main.rs with a subscriber that reads RUST_LOG through EnvFilter and switches between a JSON layer and the default text layer on a new LOG_FORMAT setting on Config, default text; document it in .env.sample. Give the existing TraceLayer a make_span_with closure that opens a request span with method, uri and request_id, taking the id from the x-request-id header or generating a UUID v4 with the uuid crate already in Cargo.toml. Enable tower-http's request-id feature and add SetRequestIdLayer and PropagateRequestIdLayer so the id is echoed on the response. Add unit tests that a supplied x-request-id is kept and a missing one yields a UUID. Run cargo fmt --check, cargo clippy and cargo test. Start the server against Postgres with LOG_FORMAT=json, call GET /api/tags with and without an x-request-id header, and paste both JSON log lines and the test output in the pull request. Do not change the routes, the SQL or the migrations.",
  "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 touches `Cargo.toml`, `Cargo.lock`, `.env.sample`, `src/main.rs`, `src/config.rs` and `src/http/mod.rs`, plus the new test module. The description shows two JSON lines from a real `GET /api/tags`: one whose `request_id` equals the header the agent sent, one whose id is a generated UUID, each with `method`, `uri`, `status` and latency from the trace layer. The `cargo test` summary and the clippy result sit under them.

On a repository with the `Rust` workflow, the pull request's checks run the same `cargo build` and `cargo test` against Postgres and then the Postman collection against the running server, so a subscriber that panics on double initialisation or a layer that breaks a route shows up there rather than in production.

A reviewer checks three things: that `cargo run` with no `LOG_FORMAT` still prints readable lines, that the `log::` calls in `error.rs` appear inside the request span rather than outside it, and that a caller-supplied `x-request-id` is echoed and not replaced. Then they point their log pipeline at `request_id` and `target`.

## Run it on every service onboarded to the log pipeline

A team moving Rust services onto one log pipeline sends a `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `Cargo.toml` and `main.rs`, so a service already on `tracing` gets only the JSON layer and the request span added, while one still on `env_logger` gets the bridge too, and each opens its own pull request.

An API key with a `webhook_url` receives `run.completed` for every run it starts, with `data.session_url` to read the pull request link and the sample lines from. `max_concurrent` defaults to 4 per key (up to 100), yet a larger batch is sent in one pass; requests over it answer `202` with `status: "queued"` and start, oldest first, when a slot frees.

## Why run it on Rush?

Changing a logger is easy to get subtly wrong: the JSON layer goes on in development where nobody can read it, the `log` bridge is forgotten so half the lines vanish, or the span is opened after the handler runs so the request id never attaches to the error. In a Rush sandbox the agent compiles the service, starts it against a real Postgres, sends real requests with `curl` and reads back the actual lines, and every `cargo` command and its output stays in the run's record next to the pull request.

The same request works on every Axum service a team owns, and nothing on a laptop changes: no toolchain upgrade, no local Postgres, no branch left half-done when the day ends. The sandbox parks when the turn finishes, and a follow-up such as adding a `user_id` field from the JWT extractor wakes it where it stopped.

## Frequently asked questions

### Will the log::error! calls in error.rs still work?

Yes. `tracing-log` installs a `log` logger that forwards every `log` record into `tracing`, so the existing calls in `error.rs` and `extractor.rs` come out in the new format, inside the request span, without touching those files. Rewriting them to `tracing::error!` is an optional follow-up.

### Does RUST_LOG keep working?

Yes. The subscriber uses `EnvFilter::from_default_env()`, which reads the same `RUST_LOG` syntax that `env_logger` did, so the `realworld_axum_sqlx=debug,tower_http=debug` line in `.env.sample` behaves as before.

### What if a load balancer already sets x-request-id?

The id function reads the header first and only generates a UUID when it is absent, so the id a gateway assigned is kept, written into the span and echoed on the response. The unit test covers both cases.

### Does this add a dependency on a logging service?

No. The output is JSON on stdout, one object per line, which Vector, Fluent Bit, Loki, Datadog and CloudWatch all ingest without an SDK. Nothing is sent anywhere by the service itself.

## More Axum jobs

- [Inventory Every API Endpoint of an Axum Service](https://getrush.ai/run/api-endpoint-inventory/axum/)
- [Dockerize an Axum API With SQLx and Postgres](https://getrush.ai/run/dockerize-app/axum/)
- [Review SQLx Migrations in Axum Pull Requests](https://getrush.ai/run/review-database-migrations/axum/)

## The same job on other stacks

- [Add Structured Logging to a .NET App](https://getrush.ai/run/add-structured-logging/dotnet/)
- [Add Structured Logging to an Echo API](https://getrush.ai/run/add-structured-logging/echo/)
- [Add Structured JSON Logging to a Fiber App](https://getrush.ai/run/add-structured-logging/fiber/)

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