# Add Slow Query Logging to an SQLx + Axum API

Yes. An agent turns on SQLx's slow-statement log at a threshold you set, quiets the per-statement noise, proves it with pg_sleep and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-slow-query-logging/sqlx/). 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 pool is opened and how logs are filtered, because SQLx already has a slow-query logger and this app never hears it. In an API laid out like launchbadge/realworld-axum-sqlx, `Cargo.lock` resolves `sqlx` to 0.5.9 with `runtime-tokio-native-tls` and `postgres`, and `src/main.rs` builds the pool with `PgPoolOptions::new().max_connections(50).connect(&config.database_url)`, where `config.database_url` is a string clap reads from `DATABASE_URL` in `src/config.rs`. SQLx 0.5.9 logs every statement under the target `sqlx::query`: at `Info` normally, and at `Warn` once a statement takes a second or more, with a line of the form `{summary}; rows: {n}, elapsed: {d}` followed by the formatted SQL. The app uses `log` 0.4.14 and `env_logger` 0.9.0, and `.env.sample` sets `RUST_LOG=realworld_axum_sqlx=debug,tower_http=debug`. That filter names two targets and `sqlx::query` is not one of them, so both the per-statement lines and the slow warnings are dropped before they reach stderr.

The change is to set the levels and the threshold on purpose. `src/main.rs` parses the URL into `PgConnectOptions` with `.parse()`, calls `.log_statements(LevelFilter::Debug)` so the per-statement line is there when someone turns on debug and silent otherwise, and `.log_slow_statements(LevelFilter::Warn, Duration::from_millis(config.slow_query_ms))`, then opens the pool with `connect_with`. Both methods come from the `sqlx::ConnectOptions` trait, which has to be in scope. `Config` in `src/config.rs` gains `slow_query_ms` as a `#[clap(long, env)]` field with a default, so the threshold is a flag or an environment variable like `DATABASE_URL` and `HMAC_KEY` are, and `.env.sample` gains the line and a sentence about it.

The filter changes too, or the new lines go nowhere. `.env.sample` and the `env` block of `.github/workflows/rust.yml` add `sqlx::query=warn` to `RUST_LOG`, so a slow statement reaches the log at `Warn` while the `Debug` per-statement lines stay off unless the operator raises that target. The agent leaves the `TraceLayer` in `src/http/mod.rs` and the `log::error!("SQLx error: {:?}", e)` in `src/http/error.rs` alone: the first times requests, the second reports failures, and neither says which statement was slow. The 24 `query!` and `query_as!` calls under `src/http/` need no change, because the logger sits in the connection and sees all of them.

The proof runs against a Postgres the agent installs from apt in its sandbox. It copies `.env.sample` to `.env` with the local URL, runs `cargo install sqlx-cli --features postgres` and `sqlx db setup` as the CI job does, and starts the server with the threshold set to a few milliseconds so a normal request's statements cross it, reading the `Warn` lines with their summaries and elapsed times from stderr. It then sets the threshold back to the default, runs a `select pg_sleep(1)` through a one-off `sqlx::query` in a test, and shows that one line and only that one at `Warn`. `cargo build` and `cargo test` run before the pull request opens.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add slow query logging to the SQLx pool. Read Cargo.toml, Cargo.lock for the sqlx version, src/main.rs, src/config.rs, src/http/mod.rs, src/http/error.rs, .env.sample and .github/workflows/rust.yml first, and explain why SQLx's own statement log never appears today. Parse DATABASE_URL into PgConnectOptions, set log_statements to Debug and log_slow_statements to Warn at a threshold from a new slow_query_ms config field with a default, and open the pool with connect_with. Add sqlx::query=warn to RUST_LOG in .env.sample and the CI workflow. Install Postgres in your sandbox, run sqlx db setup, and prove it twice: once with a tiny threshold so ordinary statements log at Warn, and once at the default with a pg_sleep statement so only that one does. Run cargo build and cargo test, and open a pull request that quotes the log lines from both runs.",
  "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 `src/main.rs`, `src/config.rs`, `.env.sample` and the `env` block of `.github/workflows/rust.yml`, and adds one test. Its description explains the `RUST_LOG` filter that was hiding the log, quotes the `Warn` lines from the low-threshold run with their `elapsed` values and the single line from the `pg_sleep` run, and includes the `cargo test` summary.

The run's record keeps the Postgres setup, the server's stderr from both runs and the build, so a reviewer sees the real line format SQLx emits rather than a description of it.

Before merging, a reviewer picks the production threshold, since the default in the pull request is a starting point and the right one depends on the slowest query the API is expected to run, and decides whether the formatted SQL that follows each line is acceptable in their log store or should be shortened, which the pull request names as a follow-up.

## Run it on every latency alert

A Grafana contact point can call a `webhook` trigger on a Project automation directly, sending `Authorization: Bearer <its secret>`, when a p95 latency alert fires; the automation runs a prompt that reads the alert and the service's recent `sqlx::query` warnings and reports which statements crossed the threshold during the window. The trigger's URL takes an `Idempotency-Key` from the alert's fingerprint, so repeat notifications for one incident do not start repeat runs.

A team with several SQLx services starts one run per repository from a script, with this `input`, the repository in `resources`, and 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 pool setup and filter, so one on SQLx 0.7 or with `tracing` instead of `log` gets the equivalent change rather than this one.

## Why run it on Rush?

The bug here is a filter string, and finding it means knowing what SQLx logs, under which target, at which level, and reading the one line in `.env.sample` that silences it. The agent reads the code and the lockfile, makes the change in the connection options where it belongs, and proves it twice against a Postgres it installed, with the actual log lines kept in the run's record.

The same job on a fleet of services runs in parallel, one sandbox each, and each pull request quotes that service's own log output, so a reviewer checks evidence rather than a pattern.

## Frequently asked questions

### Why did the slow-statement warning never show before?

SQLx 0.5.9 logs slow statements at `Warn` under the `sqlx::query` target by default, but `env_logger` only emits targets `RUST_LOG` names, and `.env.sample` names `realworld_axum_sqlx` and `tower_http`. The logger was on; the filter dropped its output.

### Why lower the per-statement level to Debug?

At its default of `Info`, every statement logs a line with its SQL, which is noise in production and a cost in a log store. Setting it to `Debug` keeps it available for a developer who raises `sqlx::query=debug` locally and keeps the slow warning as the only line that appears by default.

### Does this change any query or the pool size?

No. The 24 query macros under `src/http/` and `max_connections(50)` are untouched; the only difference is that the pool is built from parsed `PgConnectOptions` instead of a URL string, which is how SQLx exposes the logging settings.

### What does the log line contain?

The first four words of the statement as a summary, the row count, the elapsed time, and the full SQL formatted on the lines after when it is longer than the summary. Bound parameter values are not included, so a slow `SELECT … WHERE email = $1` logs the placeholder, not the email.

## More SQLx jobs

- [Upgrade SQLx From 0.5 to the Current Release in a Rust API](https://getrush.ai/run/upgrade-sqlx/sqlx/)
- [Add Cursor Pagination to a Rust API With SQLx](https://getrush.ai/run/add-cursor-pagination/sqlx/)
- [Add Database Indexes to a sqlx Project](https://getrush.ai/run/add-database-indexes/sqlx/)

## The same job on other stacks

- [Add Slow Query Logging to a TypeORM + NestJS App](https://getrush.ai/run/add-slow-query-logging/typeorm/)
- [Add Slow Query Logging to a Drizzle App](https://getrush.ai/run/add-slow-query-logging/drizzle/)
- [Add Slow Query Logging to a GORM App](https://getrush.ai/run/add-slow-query-logging/gorm/)

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