# Add Structured Logging to an Actix Web App

Yes. An agent replaces env_logger in your Actix Web app with tracing, JSON output and a span per request, keeps the existing log lines, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-structured-logging/actix/). 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 logs today before it changes a line, because the goal is JSON with a request id on every line, not a different set of messages. In an app shaped like `basics/todo` in actix/examples, `Cargo.toml` takes `actix-web 4.11`, `actix-files 0.7`, `actix-session 0.11` with the `cookie-session` feature, `env_logger 0.11`, `log 0.4`, `dotenvor` and `serde` from the workspace, plus `sqlx 0.9` on SQLite and `tera 2`. `src/main.rs` calls `env_logger::init_from_env` with `info` as the default filter, wraps the `App` in `middleware::Logger::default()`, a cookie `SessionMiddleware` and `ErrorHandlers` for 400, 404 and 500, and serves `/`, `POST /todo`, `POST /todo/{id}` and `/static`. The handlers in `src/api.rs` and the queries in `src/model.rs` log through the `log` macros, and `.env` sets `RUST_LOG=info` and `SQLX_OFFLINE=true`.

The workspace already pins what the change needs: `tracing 0.1.30`, `tracing-actix-web 0.7.22` and `tracing-subscriber 0.3` with the `env-filter` and `json` features sit in `[workspace.dependencies]`, and `tracing/custom-root-span` in the same repository shows `TracingLogger` with a custom `RootSpanBuilder`. The agent adds the three crates to `basics/todo/Cargo.toml` with `workspace = true` and removes `env_logger`. In `src/main.rs` it replaces `env_logger::init_from_env` with a `tracing_subscriber::registry()` that layers `EnvFilter::try_from_default_env()` falling back to `info`, so the existing `RUST_LOG` keeps working, and a `fmt::layer().json()` with `flatten_event(true)` and the current span's fields included, so every line carries the request's id, method, path and status.

`middleware::Logger::default()` becomes `TracingLogger::default()`, which opens one root span per request named `HTTP request` with `http.method`, `http.route`, `http.status_code` and a generated `request_id`, and closes it with the elapsed time. The `log::info!` and `log::debug!` calls in `main.rs` and the handlers are left alone: `tracing-subscriber`'s `tracing-log` bridge, on by default, turns them into events inside the current span, so the first pass changes no call sites. Where a handler has useful context, `create` in `src/api.rs` and the empty-description branch, the agent adds a `tracing::info!` with the task description length and the flash kind as fields rather than string interpolation, so they land as JSON keys. The 404 and 500 handlers in `api.rs` record the status on the span through `tracing::Span::current()`.

The todo example has no tests of its own, and the repository's `.github/workflows/ci.yml` runs `cargo check --workspace --bins --examples --tests` and `cargo test --workspace --all-features` after `sqlx migrate run` on a fresh SQLite file. The agent runs `cargo check -p todo`, `cargo clippy -p todo` and `cargo fmt --check`, then `sqlx database create`, `sqlx migrate run` and `cargo run -p todo` with `RUST_LOG=info`, makes a `GET /`, a `POST /todo` and a request to a missing path, and pastes the resulting JSON lines in the pull request, one object per line with `request_id`, `http.route` and `http.status_code` visible.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Replace env_logger with structured JSON logging in this Actix Web app and open a pull request. Read the workspace Cargo.toml, basics/todo/Cargo.toml, basics/todo/.env, basics/todo/src/main.rs, src/api.rs, src/db.rs, src/model.rs, src/session.rs and .github/workflows/ci.yml first, and look at tracing/custom-root-span/src/main.rs for the TracingLogger pattern this repository already uses. Add tracing, tracing-actix-web and tracing-subscriber from the workspace dependencies to basics/todo/Cargo.toml and remove env_logger. In main.rs build a tracing_subscriber registry with an EnvFilter from RUST_LOG defaulting to info and a JSON fmt layer that flattens events and includes span fields, and replace middleware::Logger::default() with TracingLogger::default(). Leave the existing log macro calls in place so the tracing-log bridge carries them. In api.rs add tracing::info! events with fields, not interpolation, in create and record the status on the current span in the 404 and 500 handlers. Run cargo fmt --check, cargo clippy -p todo and cargo check -p todo, then sqlx database create, sqlx migrate run and cargo run -p todo, make a GET /, a POST /todo and a request to a missing path, and paste the JSON log lines in the pull request. Do not change the routes, the templates or the SQL.",
  "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 swaps one dependency for three in `basics/todo/Cargo.toml`, replaces about ten lines in `src/main.rs`, and adds a handful of `tracing::info!` calls and two span records in `src/api.rs`. The description shows three JSON log lines captured from the running app, each with `request_id`, `http.method`, `http.route`, `http.status_code` and the elapsed time, and the `cargo clippy` output with no warnings.

The repository's CI runs `cargo check` and `cargo test` across the workspace on every pull request after applying the todo migrations, so a dependency that fails to resolve or a type error in the subscriber setup shows up there. Nothing in CI reads the log format, so the pasted lines are the evidence for the shape.

A reviewer checks that `RUST_LOG` still filters as before, that the JSON layer flattens fields rather than nesting them under `fields`, that the `request_id` appears on handler events and not only on the root span's close line, and that no `println!` or interpolated message slipped in. Then they point their log shipper at stdout and build the first dashboard on `http.route` and `http.status_code`.

## Run it on every service onboarded to central logging

A team moving its Rust services onto one log pipeline sends one `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, and one on Axum gets `tower-http`'s trace layer instead of `TracingLogger`; each opens its own pull request.

Send a `request_id` with each body so a retry returns the run already started. With a `webhook_url` on the API key, Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from, so the pipeline change and the code changes can be reviewed in one sitting.

## Why run it on Rush?

Logging changes are judged by the lines they produce, and those only exist when the app runs. In a Rush sandbox the agent builds the todo binary, creates the SQLite database the way `ci.yml` does, starts the server and makes real requests, and the JSON that came out is kept in the run's record beside the command that produced it. A reviewer reads the actual `request_id` on an actual 404 rather than inferring the format from the subscriber setup.

The repository already carries the pattern, in `tracing/custom-root-span`, and the agent reuses it rather than inventing one, which is the kind of consistency that is easy to skip on a laptop at the end of the day. The same request body works unchanged on every Actix Web service a team runs, and several run at once in their own sandboxes.

## Frequently asked questions

### Do I have to rewrite every log::info! call?

No. `tracing-subscriber` enables its `tracing-log` bridge by default, so the `log::info!` and `log::debug!` calls in `main.rs` and `model.rs` become tracing events inside the current request span without edits. The agent converts only the handler lines where adding fields is worth it.

### Why TracingLogger instead of the Logger middleware?

`middleware::Logger` writes one formatted line per request through `log`. `TracingLogger` from `tracing-actix-web` opens a span per request with `request_id`, method, route and status as fields, so every event emitted while handling that request carries them automatically. The `tracing/custom-root-span` example in this repository uses the same middleware.

### Will RUST_LOG still work?

Yes. The subscriber uses `EnvFilter::try_from_default_env()`, which reads `RUST_LOG` with the same directive syntax `env_logger` accepted, and falls back to `info` as `main.rs` did before. The `.env` file keeps its `RUST_LOG=info` line.

### Is JSON slower?

The JSON formatter does slightly more work per event than the text one, and `TracingLogger` records a few fields per request; neither does I/O beyond the write to stdout that already happened. A reviewer who wants readable local output switches the layer on `RUST_LOG_FORMAT` or a similar variable; the pull request ships JSON by default and notes the one line to change.

## More Actix Web jobs

- [Dockerize an Actix Web App](https://getrush.ai/run/dockerize-app/actix/)
- [Fix Actix Web Errors from Sentry Alerts](https://getrush.ai/run/fix-sentry-errors/actix/)
- [Review Pull Requests on an Actix Web API](https://getrush.ai/run/review-pull-requests/actix/)

## The same job on other stacks

- [Add Structured Logging to an aiohttp App](https://getrush.ai/run/add-structured-logging/aiohttp/)
- [Add Structured Logging to an Axum API](https://getrush.ai/run/add-structured-logging/axum/)
- [Add Structured Logging to a .NET App](https://getrush.ai/run/add-structured-logging/dotnet/)

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