# Add Structured Logging to a Litestar App

Yes. An agent switches your Litestar app to JSON logs with structlog, adds request and response logging with secrets masked, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-structured-logging/litestar/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads what the app logs today, which in a small Litestar service is usually nothing of its own. In litestar-org/litestar-hello-world, `app.py` defines two handlers, `GET /async` (which awaits `sleep(0.1)`) and `GET /sync` with `sync_to_thread=False`, and builds `Litestar(route_handlers=[sync_hello_world, async_hello_world])` with no `logging_config` and no middleware. `pyproject.toml` depends on `litestar[standard]>=2.4.1`, and `pdm.lock` pins litestar 2.4.1 and uvicorn 0.24.0.post1; `requires-python` is `>=3.8,<4.0`, Ruff runs with `select = ["ALL"]` at a 120-column limit, mypy is `strict`, and `pdm run ci` is `lint` then `test`. `tests/test_app.py` has two `TestClient` tests, and `.github/workflows/ci.yaml` runs pre-commit plus pytest on Python 3.8 through 3.11.

Litestar 2 has structlog support built in, so the agent adds the `structlog` extra rather than a third-party package: the dependency becomes `litestar[standard,structlog]>=2.4.1` and `pdm lock` updates the lockfile. In `app.py` it passes `logging_config=StructLoggingConfig()` from `litestar.logging.config`. The default processor chain merges contextvars, adds the level, formats exception info, stamps an ISO timestamp and renders JSON, so every line the app or the framework logs becomes one JSON object on standard output. The agent keeps the defaults and adds one processor of its own only if a reviewer asks, because the point of the change is machine-readable output, not a custom format.

Request logging comes from `LoggingMiddlewareConfig` in `litestar.middleware.logging`, added to the app's `middleware` list. The agent sets `request_log_fields` to `path`, `method`, `query` and `path_params` and `response_log_fields` to `status_code`, deliberately leaving `body` and `headers` out of both so a log line never carries a payload. The middleware obfuscates the `Authorization` and `X-API-KEY` headers and the `session` cookie by default, which the agent states in the pull request. For correlation it adds a `before_request` hook that binds a `correlation_id` into structlog's contextvars, taken from an incoming `X-Request-ID` header or generated, so the request line, the response line and anything a handler logs in between share it.

Tests prove the shape, not the presence, of a log line. `tests/test_logging.py` uses `TestClient`, calls `/sync` with an `X-Request-ID` header, captures standard output with `capfd`, parses each line with `json.loads`, and asserts a request event and a response event with `status_code` 200 and the same `correlation_id`; a second test sends an `Authorization` header and asserts the value never appears in the output. The agent runs `pdm install`, `pdm run lint` (pre-commit with Ruff, codespell and mypy strict) and `pdm run test` as `pyproject.toml` and the workflow define them, and keeps `from __future__ import annotations` so the file still passes on Python 3.8.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add structured JSON logging to this Litestar application. Read app.py, pyproject.toml, pdm.lock, tests/test_app.py, Makefile and .github/workflows/ci.yaml first. Add the structlog extra to the litestar dependency and update pdm.lock. In app.py pass logging_config=StructLoggingConfig() and add LoggingMiddlewareConfig with request_log_fields limited to path, method, query and path_params and response_log_fields limited to status_code, so no body or header values are logged. Add a before_request hook that binds a correlation_id from the X-Request-ID header, or a new uuid4, into structlog contextvars. Write tests/test_logging.py that captures stdout with capfd, parses each line as JSON, and asserts the request and response events share the correlation_id and that an Authorization header value never appears. Keep the code valid on Python 3.8. Run pdm install, pdm run lint and pdm run test, and open a pull request that shows two sample log lines.",
  "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 `app.py`, `pyproject.toml` and `pdm.lock` and adds `tests/test_logging.py`. The description shows two JSON lines from a request to `/sync`, one for the request and one for the response, with the shared `correlation_id`, and lists the fields logged and the ones deliberately left out.

The run's record keeps the `pdm run lint` and `pdm run test` output, so a reviewer sees that Ruff's `ALL` rule set and strict mypy accepted the new code and that the four tests pass, without pulling the branch.

Before merging, a reviewer decides whether to also log `headers` with the default obfuscation, whether uvicorn's own access log should be turned off now that the middleware logs each request, and where the JSON lines go in production, since the config writes to standard output and leaves shipping to the platform.

## Run it on every Python service repository

A team standardising on JSON logs across its Litestar services starts one run per repository from its own server: a `POST /o/{org}/sessions` each, with that 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 instead of opening a second pull request.

Afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request adds a route handler or middleware, confirm it logs through the app's structlog config and adds no print() or bare logging call; comment with file and line otherwise" keeps new code on the same output. The trigger adds the pull request after the prompt; only work by an owner, member or collaborator fires it.

## Why run it on Rush?

Logging changes are judged on the output, and the output only exists when the app runs: whether a header value leaks, whether the request and response lines share an id, whether the lockfile still resolves. The agent runs the app's own test client in its own sandbox and leaves a test that parses the lines as JSON, so the format is checked on every push rather than eyeballed once.

Every command the agent ran stays with the run, so the pull request can paste the sample lines and the passing lint and test output rather than describe them. Several services can get the same change at once, each on its own machine with its own record.

## Frequently asked questions

### Why structlog and not the standard logging module with a JSON formatter?

Litestar ships a `StructLoggingConfig` and a `structlog` extra, so the integration is first-party and the request logging middleware emits structured events into it directly. A JSON formatter on the standard library would format messages after the fact and lose the per-request contextvars binding.

### Will request bodies or tokens end up in the logs?

No. The agent leaves `body` and `headers` out of both field lists, and the middleware masks `Authorization`, `X-API-KEY` and the `session` cookie by default if headers are ever added. A test sends an `Authorization` header and asserts its value is absent from the output.

### Does this still support Python 3.8?

Yes. The project's `requires-python` is `>=3.8,<4.0` and the CI matrix starts at 3.8, so the agent keeps `from __future__ import annotations`, avoids newer syntax, and runs the suite under the version the sandbox has while relying on the workflow matrix for the rest.

### What about uvicorn's access log?

With the middleware logging each request, uvicorn's own access line is a duplicate in a different format. The agent does not silence it in this change, because how the app is served in production is outside the repository, and says in the pull request how to turn it off at the server.

## More Litestar jobs

- [Add WebSockets to a Litestar App](https://getrush.ai/run/add-websockets/litestar/)
- [Upgrade Python Dependencies Weekly for a Litestar App](https://getrush.ai/run/upgrade-python-dependencies/litestar/)
- [Write Pytest Tests for a Litestar App](https://getrush.ai/run/write-pytest-tests/litestar/)

## The same job on other stacks

- [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/)
- [Add Structured Logging to a Quarkus App](https://getrush.ai/run/add-structured-logging/quarkus/)

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