# Add Request ID Logging to an aiohttp App

Yes. An agent gives each request to your aiohttp app an X-Request-ID, prints it in the access and error logs, returns it in the response, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-request-id-logging/aiohttp/). 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, because aiohttp has two loggers in play and a request id has to reach both. In an app like the polls demo in aio-libs/aiohttp-demos, `aiohttpdemo_polls/main.py` builds the `web.Application` in `init_app`, stores the YAML config under `config_key`, sets up Jinja2, appends `pg_context` to `cleanup_ctx`, then calls `setup_routes`, `setup_static_routes` and `setup_middlewares`; `main()` calls `logging.basicConfig(level=logging.DEBUG)` and `web.run_app(app, host=..., port=...)` with no `access_log_format`, so each request is written by the `aiohttp.access` logger in the default format, `%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"`. `middlewares.py` holds one middleware, built by `create_error_middleware`, that renders `404.html` and `500.html` and logs unexpected exceptions with `request.protocol.logger.exception("Error handling request")`, which goes to the `aiohttp.server` logger. Nothing ties that traceback to the access line it belongs to. `routes.py` registers `/`, `/poll/{question_id}`, `/poll/{question_id}/results`, `/poll/{question_id}/vote` and a static route; `requirements-dev.txt` pins aiohttp 3.13.5, pytest 9.1.1 and pytest-aiohttp 1.1.1; `pytest.ini` sets `asyncio_mode = auto` and `filterwarnings = error`; and `tests/conftest.py` builds the app from `config/polls_test.yaml` against a running PostgreSQL.

The id is made in one place. The agent adds a `request_id_middleware` to `middlewares.py` and puts it first in `setup_middlewares`, before the error middleware, because in aiohttp the first entry of `app.middlewares` is the outermost, and the error handler has to see the id when it logs. The middleware takes an inbound `X-Request-ID` header when it is present, printable and at most 128 characters, so an id a reverse proxy already assigned is kept, and otherwise makes a `uuid.uuid4()`. It stores the value on the request under a `request_id` key, sets a module-level `contextvars.ContextVar` for the rest of the request, and writes the id into the `X-Request-ID` header of whatever response the handler returns. An `HTTPException` is a response in aiohttp, so when one is raised the middleware adds the header to the exception's headers before re-raising it, and a 404 answered by the error middleware's template carries the id too.

Then the two log streams. For the access log, `main.py` passes `access_log_format='%a %t "%r" %s %b %Tf "%{X-Request-ID}o"'` to `web.run_app`: `%{FOO}o` is aiohttp's directive for a response header, so the id the middleware set is printed on the same line as the status and the time the request took. For everything else, a `logging.Filter` reads the context variable and sets `record.request_id` on each record, defaulting to `-` outside a request, and `logging.basicConfig` in `main()` gets a `format` that includes `%(request_id)s`, so the `aiohttp.server` traceback from the error middleware and any `logging` call in `views.py` or `db.py` carries the same id without touching those modules. `get_app()`, which aiohttp-devtools uses for local development, picks up the middleware through `init_app` and needs no change.

The tests do not need PostgreSQL. `tests/test_request_id.py` builds a bare `web.Application`, calls `setup_middlewares` on it and adds two handlers, one that returns 200 and one that raises `RuntimeError`, then uses the `aiohttp_client` fixture to assert that a response without an inbound header carries a UUID in `X-Request-ID`, that an inbound `X-Request-ID: abc-123` is echoed, that a 300-character inbound value is replaced, that a 404 and the rendered 500 both carry the header, and, with `caplog`, that the `aiohttp.server` record for the exception carries a `request_id` attribute that matches the response header. In its sandbox the agent runs `make flake`, which `demos/polls/Makefile` defines as `flake8 aiohttpdemo_polls`, and `pytest tests` under the `filterwarnings = error` setting, with a PostgreSQL it installs from the system packages and configures as `config/polls_test.yaml` expects so the existing integration tests run too. It then starts the app with `python -m aiohttpdemo_polls`, requests `/` and `/no-such-route`, and pastes the two access lines into the pull request.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add request id logging to this aiohttp application. Read aiohttpdemo_polls/main.py, middlewares.py, routes.py, views.py, db.py, typedefs.py, requirements-dev.txt, pytest.ini, tests/conftest.py and the Makefile first. Add a middleware, registered before the existing error middleware, that takes a valid inbound X-Request-ID header or generates a UUID, stores it on the request and in a contextvar, and sets X-Request-ID on every response including HTTPException responses and the rendered 404 and 500 pages. Pass an access_log_format to web.run_app that prints the response's X-Request-ID with the status and the request time. Add a logging filter that puts the request id on every log record and include it in the basicConfig format so the error middleware's traceback carries it. Write tests that need no database for the generated id, the echoed id, an oversized inbound id, the header on 404 and 500, and the id on the error log record. Run flake8 and pytest, start the app and capture two access 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 `aiohttpdemo_polls/middlewares.py` and `aiohttpdemo_polls/main.py` and adds `tests/test_request_id.py`. The description shows two access log lines from the sandbox, one for `/` and one for a 404, each ending in the request id, and one `aiohttp.server` traceback line prefixed with the same id, together with the pytest summary listing the new tests.

The run's record keeps the flake8 and pytest output, the server start and the two requests, so a reviewer sees the id travelling from header to access line to error line rather than reading about it.

Before merging, a reviewer decides whether to trust an inbound `X-Request-ID` at all or always mint one at this hop, whether the templates should print the id on the 500 page so a user can quote it, and whether the Gunicorn deployment, if there is one, sets `access_logformat` to the same string, since Gunicorn's own format setting replaces aiohttp's. Handlers, routes and the database layer are unchanged.

## Run it on every service whose errors cannot be matched to a request

A team with several aiohttp services starts one run per repository from its own server: one `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 rather than a second pull request. Each run reads that service's own middleware list and log configuration, so one that already uses structlog gets the id bound there instead of a `logging.Filter`.

After that, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a middleware to setup_middlewares or changes logging configuration, check that the request id middleware is still first and that the access log format still prints X-Request-ID, and comment with what changed" guards the order on every change. The trigger puts the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

A request id is a five-line middleware and three places that have to agree: the response header, the access log format and the error log's record attributes. The common failure is getting two of the three, so the access line has an id the traceback lacks. The agent reads where each log line comes from in this app and changes the format strings and the middleware order together, then proves it with a test that raises on purpose and reads the log record.

On Rush the lint, the tests and the live requests happen in the run's own sandbox and their output is kept with the run, so the pull request carries the two access lines it claims. Several services can get the same treatment at once, each as its own run and pull request.

## Frequently asked questions

### Should the app trust an inbound X-Request-ID?

Only within limits. Keeping the id a reverse proxy or a calling service already assigned is what makes one id span several hops, so the middleware accepts an inbound value that is printable and at most 128 characters and replaces anything else with a fresh UUID. If the app is reached directly by clients, the pull request shows the one-line change to always mint the id here.

### Why a contextvar and a logging filter instead of passing the id around?

Because the modules that log, `db.py`, `views.py` and the error middleware, never see the response object. A `contextvars.ContextVar` set in the middleware is visible to every `await` in that request and to no other request on the same loop, and a `logging.Filter` copies it onto each record, so existing `logging` calls gain the id without an edit.

### Why %{X-Request-ID}o rather than the request header?

The `o` directive reads the response header and the `i` directive reads the request header. The middleware writes the final id to the response whether it came from the client or was generated, so the response header is the one value that is always set and always the id the app actually used.

### Does this work under Gunicorn?

The middleware and the filter do. The access log format does not come from `web.run_app` there: aiohttp's Gunicorn worker takes Gunicorn's `access_logformat` setting, which must use aiohttp's directives, and writes the access log only when `accesslog` is set. The pull request names the setting to copy the same format string into.

## More aiohttp jobs

- [Add Request Timeouts to an aiohttp App](https://getrush.ai/run/add-request-timeouts/aiohttp/)
- [Add Security Headers to an aiohttp App](https://getrush.ai/run/add-security-headers/aiohttp/)
- [Add Structured Logging to an aiohttp App](https://getrush.ai/run/add-structured-logging/aiohttp/)

## The same job on other stacks

- [Add Request ID Logging to a chi App](https://getrush.ai/run/add-request-id-logging/chi/)
- [Add Request ID Logging to a Cloudflare Worker](https://getrush.ai/run/add-request-id-logging/cloudflare-workers/)
- [Add Request ID Logging to a CodeIgniter 4 App](https://getrush.ai/run/add-request-id-logging/codeigniter/)

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