# Add Request ID Logging to a Litestar App

Yes. An agent adds an X-Request-ID middleware to your Litestar app, binds the id into structlog's context so every log line carries it, tests it and opens a PR.

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

## What the agent does

In an app like litestar-org/litestar-fullstack, the agent starts from how logging is wired. `pyproject.toml` installs `litestar[jinja,jwt,structlog,cryptography,pydantic]` with Advanced Alchemy, `litestar-saq`, `litestar-vite` and `litestar-granian`. `src/py/app/server/plugins.py` builds `StructlogPlugin(config=config.log)`, and `config.log` comes from `LogSettings.get_structlog_config()` in `src/py/app/lib/settings.py`: `enable_middleware_logging=False`, a processor chain from `lib/log.py` whose first entry is `structlog.contextvars.merge_contextvars` in both the JSON chain used off a TTY and the console chain used on one, a stdlib bridge through `ProcessorFormatter` for `sqlalchemy.engine`, `saq`, `granian.access` and the rest, and a `LoggingMiddlewareConfig` whose `request_log_fields` default to `path`, `method`, `query` and `path_params` and `response_log_fields` to `status_code`, read from `LOG_REQUEST_FIELDS` and `LOG_RESPONSE_FIELDS`, with `Authorization`, `X-API-KEY` and `X-XSRF-TOKEN` obfuscated. `lib/log.py` also defines a `StructlogMiddleware` that clears the context per request and a `BeforeSendHandler`, neither of which anything under `server/` registers. `ApplicationCore.on_app_init` in `server/core.py` is where `app_config` is assembled, `/health` lives in `domain/system/controllers.py`, and `src/py/tests/integration/system/routes/test_health.py` calls it through the `client` fixture.

The agent adds `RequestIdMiddleware` to `lib/log.py`, next to the middleware already there, as a plain ASGI callable so it costs nothing per request beyond a header read. On an `http` or `websocket` scope it looks for `x-request-id` in `scope["headers"]`, keeps the value when it is 1 to 128 characters of letters, digits, dots, underscores and hyphens, and makes a `uuid4()` otherwise, so a client cannot inject a log line through the header. It clears the structlog context, binds `request_id`, stores the id in `scope["state"]` for handlers, and wraps `send` to add `x-request-id` to the `http.response.start` message, so every response names its id whether a handler, a guard or an exception produced it. `ApplicationCore.on_app_init` appends it to `app_config.middleware`; that hook runs before the structlog plugin's own `on_app_init` adds the logging middleware, which is what puts the binding ahead of the request line, and a test below checks that order rather than assuming it.

With the id in the context, the agent turns `enable_middleware_logging` on in `get_structlog_config`, so the `LoggingMiddlewareConfig` that is already written produces one request line and one response line per call, and `merge_contextvars` stamps `request_id` on both and on anything a handler or service logs in between. For the stdlib bridge it reads `stdlib_logger_processors` and adds `merge_contextvars` there if it is missing, so SQLAlchemy's statement log and Granian's access line carry the same id as the structlog lines around them. The problem-details responses that `exception_to_http_response` builds gain a `request_id` member, so a person reporting an error can quote the value a log search needs, and the `after_exception_hook_handler` that binds `exc_info` leaves the error line with both the traceback and the id.

Tests go in `src/py/tests/integration/system/routes/test_request_id.py` next to the health tests, on the same `client` fixture: a `GET /health` answers with an `x-request-id` header that parses as a UUID; a request sent with `X-Request-ID: abc-123` gets `abc-123` back; a 300-character value is replaced; and inside `structlog.testing.capture_logs()` the request line for the call carries the same `request_id` as the header. The agent runs `uv sync --all-groups`, `uv run pre-commit run --all-files` for the `linting` group (ruff, mypy, pyright, slotscheck, codespell) and `uv run pytest`; the integration suite starts Postgres through `pytest-databases`, which needs Docker, so it installs `docker.io`, starts `dockerd` and runs the suite the way `ci.yaml` does on Python 3.12 and 3.13.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add request ID logging to this Litestar app. Read pyproject.toml, src/py/app/server/core.py, src/py/app/server/plugins.py, src/py/app/lib/log.py, src/py/app/lib/settings.py, src/py/app/lib/exceptions.py, src/py/app/domain/system/controllers.py, the tests under src/py/tests/integration/system and .github/workflows/ci.yaml first. Add an ASGI middleware that reads X-Request-ID when it is short and made of safe characters, generates a UUID otherwise, binds it into structlog's context variables, stores it in the scope state and sets it on every response. Register it so it runs before the request is logged. Enable the structlog plugin's middleware logging with the request and response fields already configured, make sure standard-library log records carry the id too, and add the id to error responses. Write integration tests for the header, the echo, the rejection and the log line. Run the linters and the test suite, and open a pull request with the output.",
  "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

The pull request changes `src/py/app/lib/log.py`, `src/py/app/lib/settings.py`, `src/py/app/server/core.py` and `src/py/app/lib/exceptions.py`, and adds `src/py/tests/integration/system/routes/test_request_id.py`. Its description shows one request's log lines in the JSON form with `request_id` on the request line, a SQLAlchemy statement and the response line, the response headers, and the error body with its `request_id` member.

The `Tests and Linting` workflow runs on the pull request: the `validate` job with pre-commit and the `test` job on both Python versions, where the new tests run beside the health tests. The run's record keeps the pre-commit output and the full pytest run from the sandbox.

Before merging, a reviewer decides whether a client-supplied id should be accepted at all or only from a trusted proxy, whether `/health` should be excluded from the request lines now that they are on, and whether SAQ jobs should inherit the id of the request that enqueued them. The routes, the models and the frontend are unchanged.

## Run it on every Linear issue labelled observability

A team that files observability work in Linear adds an automation on the Project with a `linear` trigger on issues labelled `observability` and this prompt. When an issue such as "log lines need a request id we can search on" gets the label, a run starts in the repository, does the work above against that repository's own logging setup, and opens a pull request that links the issue. The trigger adds the issue after the prompt, so one prompt serves every such issue.

The same body sent to `POST /o/{org}/sessions` by hand, with a `request_id` that is a UUID v5 of the issue's identifier, does the same for one issue. The key's `webhook_url` reports each run the key starts with the pull request in `result`; a run an automation starts appears in the Project's run list and has its own `max_runs_per_hour` cap.

## Why run it on Rush?

A request id is only useful if it reaches every line, and in a structlog app that depends on things a reader cannot see from the diff: which processor chain each logger uses, whether the context is cleared before or after the request line is written, and where the middleware sits relative to the one that logs. The agent reads the chains and the plugin order, writes a test that would fail if the order were wrong, and runs the suite with a real Postgres in its own sandbox.

The sample log lines, the pre-commit run and the pytest output stay with the run and are quoted in the pull request. A team with several Litestar services gets the same change per repository, each checked against that service's own settings and tests.

## Frequently asked questions

### Why not use the StructlogMiddleware that is already in log.py?

It only clears the context variables; nothing binds a request id, and nothing registers it. The agent's middleware does the clear and the bind in one place and sets the response header too, so the existing class becomes redundant and the pull request removes it rather than leaving two ways to do the same thing.

### Why turn on the plugin's middleware logging instead of writing request lines by hand?

The `LoggingMiddlewareConfig` is already configured with the fields and the obfuscated headers; it just was not enabled. Turning it on gives a request and a response line per call that go through the same processors as every other structlog line, so `merge_contextvars` adds the id without further code.

### Should the app trust an X-Request-ID the client sends?

Accepting it lets a gateway or a frontend correlate its own logs with the app's, which is the point of the header. The middleware limits it to 128 safe characters so it cannot carry a log injection, and the pull request shows where to restrict acceptance to a trusted proxy's address if the app faces the internet directly.

### Do SAQ background jobs get the id?

Not in this pull request. A job runs in a worker process with its own context, so the id has to travel in the job's arguments and be bound again when the job starts. The description names the `enqueue` calls to change and the worker hook to bind it in, as a follow-up.

## More Litestar jobs

- [Add Response Caching to a Litestar App](https://getrush.ai/run/add-response-caching/litestar/)
- [Add Security Headers to a Litestar App](https://getrush.ai/run/add-security-headers/litestar/)
- [Add Soft Delete to a Litestar App](https://getrush.ai/run/add-soft-delete/litestar/)

## The same job on other stacks

- [Add Request ID Logging to an Express and Mongoose API](https://getrush.ai/run/add-request-id-logging/mongoose/)
- [Add Request ID Logging to a NestJS API](https://getrush.ai/run/add-request-id-logging/nestjs/)
- [Add Request ID Logging to a Quarkus API](https://getrush.ai/run/add-request-id-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/)
