# Add Structured Logging to a Leptos Axum App

Yes. An agent adds tracing with JSON lines and a span per request to the Axum server behind your Leptos app, kept behind the ssr feature, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-structured-logging/leptos/). 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 server is built before it adds a logger, because a Leptos app compiles twice and only one of the two targets can log to stdout. In a project generated from leptos-rs/start-axum, `Cargo.toml` depends on `leptos`, `leptos_router` and `leptos_meta` at 0.8 and keeps `axum` 0.8, `leptos_axum` and `tokio` optional behind the `ssr` feature, with `wasm-bindgen` and `console_error_panic_hook` behind `hydrate`; `[package.metadata.leptos]` sets `bin-features = ["ssr"]`, `lib-features = ["hydrate"]`, `site-addr = "127.0.0.1:3000"` and `env = "DEV"`. `src/main.rs`, under `#[cfg(feature = "ssr")]`, reads the configuration with `get_configuration(None)`, builds an axum `Router` with `leptos_routes` and `fallback(leptos_axum::file_and_error_handler(shell))`, prints one line, `listening on http://` and the address, through the `log` macro in `leptos::logging`, and calls `axum::serve`. `src/lib.rs` holds the `hydrate` entry point and `src/app.rs` the `shell`, `App` and `HomePage` components. There is no `tracing`, no tower layer and no per-request output of any kind: a request that returns 404 through the fallback leaves no trace on the server.

The dependencies go in as optional crates added to the `ssr` feature list, so `cargo leptos build`, which compiles the library for `wasm32-unknown-unknown` with `hydrate`, never sees them: `tracing`, `tracing-subscriber` with its `env-filter` and `json` features, and `tower-http` with its `trace` feature. The agent checks the versions fit before it adds them: `axum` 0.8 depends on `tower` 0.5 and `http` 1, and the current `tower-http` release, 0.7 as of the day it checks, builds on the same `tower` 0.5 and `http` 1, so `cargo add tower-http --features trace --optional` resolves without a second copy of either. In `main.rs` the subscriber is set up before the router: `tracing_subscriber::fmt()` with `EnvFilter::try_from_default_env()` falling back to `info`, so `RUST_LOG` works as developers expect, and the formatter chosen from `leptos_options.env`, the value `env` in `Cargo.toml` sets: a human-readable layout in `DEV`, JSON lines in `PROD`. The `leptos::logging` call becomes a `tracing::info` event with `addr` as a field rather than text inside a formatted string.

The span per request is `TraceLayer::new_for_http()` added to the `Router` with `.layer(...)`, which opens a `request` span carrying the method, URI and HTTP version and records the status and latency when the response is written. The agent sets `DefaultOnResponse::new().level(Level::INFO)` so a request line appears at the default filter rather than only at `debug`, and `DefaultMakeSpan::new().include_headers(false)` so cookies and authorisation headers never reach the log. Because `leptos_routes` and the fallback handler run inside the layer, a `tracing::info` event inside a Leptos server function or an error from `file_and_error_handler` is emitted within the request span and inherits its fields. In DEV the lines read as before with the fields appended; in PROD each line is one JSON object with `timestamp`, `level`, `fields`, `target` and the span's `method`, `uri` and `status`, which is what a log pipeline ingests without a parser.

The test lives in `main.rs` behind `#[cfg(all(test, feature = "ssr"))]`. It builds the router with a subscriber whose writer is an in-memory buffer and the JSON formatter forced on, sends `GET /` and `GET /missing` through `tower::ServiceExt::oneshot`, which needs `tower` with its `util` feature as a dev-dependency, then parses each line as JSON and asserts one record per request with the `method`, `uri` and a `status` of 200 and 404. In its sandbox the agent installs the nightly toolchain when `rust-toolchain.toml` is present and stable otherwise, adds the `wasm32-unknown-unknown` target, installs `cargo-leptos` and `sass` as the README lists, runs `cargo fmt --check`, `cargo clippy --features ssr`, `cargo test --features ssr`, `cargo leptos build` to prove the WebAssembly side still compiles, and starts the server with `cargo leptos serve`, requests `/` and `/missing`, and copies the two resulting lines into the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add structured logging to the Axum server of this Leptos application. Read Cargo.toml, src/main.rs, src/lib.rs, src/app.rs, rust-toolchain.toml, README.md and end2end/package.json first. Add tracing, tracing-subscriber with env-filter and json, and tower-http with the trace feature as optional dependencies enabled only by the ssr feature, checking that the tower-http version shares tower and http versions with the axum release in Cargo.toml. In src/main.rs initialise a tracing subscriber before building the router, with an EnvFilter from RUST_LOG falling back to info, JSON output when the Leptos env is PROD and a readable format in DEV, and replace the leptos logging macro with a tracing event. Add TraceLayer::new_for_http to the router with responses logged at info and request headers excluded. Write a test behind cfg(test) and the ssr feature that drives the router with oneshot, captures the JSON output in a buffer and asserts one record per request with method, uri and status for a 200 and a 404. Run cargo fmt, clippy and the tests with the ssr feature, run cargo leptos build to confirm the WebAssembly target still compiles, start the server and capture two log lines, and open a pull request.",
  "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 changes `Cargo.toml` and `src/main.rs` and adds `Cargo.lock` entries for the three crates and the `tower` dev-dependency. The description shows two log lines from the running server, one JSON object for `GET /` with status 200 and one for a missing path with 404, the `cargo test --features ssr` output with the new test, and the `cargo leptos build` summary that proves the `hydrate` build still compiles without the new crates.

The run's record keeps the toolchain setup, `clippy`, the test run, the build and the two requests, so a reviewer can see that the WebAssembly bundle was built after the change and not assumed.

Before merging, a reviewer decides whether the JSON formatter should be chosen by an explicit variable rather than the Leptos env, whether the health or static asset paths under `/pkg/` should be excluded from the request span to keep the log quiet, and whether to add a request id to the span through tower-http's `request-id` feature next. `src/app.rs`, the components and the client build are unchanged.

## Run it on every service onboarded to central logging

A team moving its services onto one log pipeline sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`, with a `request_id` that is a UUID v5 of the repository's full name so a retried call returns the run already started. Each run reads that service's own feature flags and server entry point, so an Actix or plain Axum service gets the same subscriber and layer where its router is built, and each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request link and the captured log lines from.

## Why run it on Rush?

In a Leptos project the easy mistake is adding `tracing-subscriber` or `tower-http` as plain dependencies, which breaks the WebAssembly build the next time `cargo leptos build` runs, or logging request headers and shipping cookies to the log pipeline. The agent reads the feature layout first, adds the crates behind `ssr`, excludes headers, and then builds both targets to prove it.

On Rush the toolchain, the build for both targets and the live requests run in the run's own sandbox with their output kept, so the pull request carries the two JSON lines it claims. Several services can be moved onto structured logs at once, one run and one pull request each.

## Frequently asked questions

### Why keep the logging crates behind the ssr feature?

Because the same crate compiles twice: once as the server binary with `ssr` and once as a WebAssembly library with `hydrate`. `tokio`-flavoured crates and a stdout subscriber have no place in the browser bundle, and an unconditional dependency can fail that build or bloat it. Making them optional and listing them under `ssr` in `Cargo.toml` follows what the template already does for `axum` and `leptos_axum`.

### Why JSON only in production?

A developer running `cargo leptos watch` wants lines a person can read; a log pipeline wants one object per line it can index. `leptos_options.env` already distinguishes the two through the `env` setting in `Cargo.toml`, so the formatter follows it, and `RUST_LOG` filters both the same way. The pull request notes the one-line change to key it on a dedicated variable instead.

### Does it log request bodies or headers?

No. `TraceLayer` records the method, URI, version, status and latency, and the agent leaves `include_headers` off so `Cookie` and `Authorization` never appear. A `tracing::info` event in a server function is the only way application data reaches the log, and it inherits the request span's fields rather than repeating them.

### How do I turn the request lines off or up?

With `RUST_LOG`, which `EnvFilter` reads: `RUST_LOG=warn` silences the per-request lines, `RUST_LOG=info,tower_http=debug` adds the layer's own debug events, and a crate-specific directive such as `my_app=trace` raises one target. The fallback when the variable is unset is `info`, which prints one line per request and the startup line.

## More Leptos jobs

- [Add Tailwind CSS to a Leptos App](https://getrush.ai/run/add-tailwind/leptos/)
- [Add WebSockets to a Leptos App](https://getrush.ai/run/add-websockets/leptos/)
- [Add Response Compression to a Leptos Axum App](https://getrush.ai/run/add-compression/leptos/)

## The same job on other stacks

- [Add Structured Logging to a Litestar App](https://getrush.ai/run/add-structured-logging/litestar/)
- [Add Structured Logging to a Node.js App from a Linear Issue](https://getrush.ai/run/add-structured-logging/nodejs/)
- [Add Structured Logging to a Phoenix LiveView App](https://getrush.ai/run/add-structured-logging/phoenix-liveview/)

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