# AI Gateway Request Log

URL: https://www.elchi.io/docs/ai-gateway/request-log

> One row per LLM request — who, what model, which provider, tokens, status and timing — with optional prompt and answer content that is masked and encrypted on the edge and only the control plane can open.

The request log keeps **one row per LLM request** that passes through a gateway. A row records the gateway, the consumer, the model, the provider that served the request, tokens, status, duration and ids. You choose how much is kept for each gateway:

- **Off**: nothing.
- **Metadata** (the default): the row, no message content.
- **Full**: the row plus the prompts and answers. The edge masks sensitive data in them, then encrypts them to the project's key **before they leave the edge**. Only the Elchi control plane can open them, and each opening is written to the audit log.

MCP tool calls are not request-log rows. They go to the [MCP call log](https://www.elchi.io/docs/ai-gateway/mcp/call-log).

![Request log](https://www.elchi.io/docs/img/docs/aigw-requests-light.webp)

## How a row is made

```mermaid
flowchart LR
    X["Agent Router extproc<br/>(GenAI span per request)"] -->|"OTLP/gRPC<br/>127.0.0.1:9003 only"| R["elchi-ai-gateway<br/>request log receiver"]
    R --> P{"gateway's<br/>capture level"}
    P -->|off| D["dropped"]
    P -->|metadata| M["row without content"]
    P -->|full + sampled| F["mask (sensitive-data policy)<br/>truncate (maxContentBytes)<br/>encrypt (age, project key)"]
    F --> M2["row + content_enc"]
    M --> CH[("ClickHouse<br/>elchi_ai_gateway_requests")]
    M2 --> CH
    M -.optional.-> O["external OTLP endpoint"]
    M2 -.optional.-> O
```

1. The extproc emits an OpenTelemetry GenAI span for each model request and exports it to the supervisor's receiver on the edge's loopback. The span carries the content: the receiver gets it unmasked, which is why it accepts loopback only.
2. The supervisor applies the gateway's capture policy in its own process. Changing a gateway's level is a configuration reload that does not restart the extproc, and it takes effect at once.
3. At **Full**, the content is masked, truncated and encrypted before the row is queued.
4. Rows are written to ClickHouse in batches. They can also go to an [external OTLP endpoint](#forwarding-to-an-otlp-endpoint).

The span's gateway, consumer, request id and session id come from request headers that Envoy maps onto it:

| Header | Column |
|---|---|
| `x-elchi-ai-gateway` | `gateway` (set by the gateway's header filter) |
| `x-elchi-consumer` | `consumer` (set by the authorization on keyed gateways) |
| `x-request-id` | `request_id` |
| `agent-session-id` | `session_id` |

A client that sends `agent-session-id` gets its requests grouped by session, and you can [erase a whole session](#erasing).

## Capture settings (per gateway)

![Gateway form](https://www.elchi.io/docs/img/docs/aigw-gateway-form-light.webp)

| UI field (gateway page → **Request log**) | API (`gateway.capture.…`) | Default | Range | Effect |
|---|---|---|---|---|
| **Level**: Off / Metadata: model, tokens, status, ids / Full: metadata and the content, masked and encrypted | `level`: `off` \| `metadata` \| `full` | `metadata` | | What the edge keeps for each request of this gateway. |
| **Retention (days)** (Metadata and Full) | `retentionDays` | 7 | 1–365 | Each row's own TTL. The value applies to rows written after the change. Rows already written keep the retention they were written with. |
| **Content sample rate** (Full) | `sampleRate` | 1 | 0–1 | Share of requests whose **content** is kept. Every request still gets its metadata row. The choice is deterministic per trace. |
| **Max content bytes** (Full) | `maxContentBytes` | 65536 | 256–1048576 | Each content field is cut to this size. A cut field ends with `…[truncated N bytes]` and the row is marked truncated. |

When you choose **Full**, the form shows "Full capture keeps prompts and answers": the edge masks the sensitive data its policy names, then encrypts the content to this project's key. Only Owners and Admins can read it, and every read is audited. Keep the retention short.

### Set it in the UI

1. **AI Gateway → Gateways**, click the gateway (or **New gateway**).
2. In **Request log**, choose the **Level**, then **Retention (days)**, and for Full, **Content sample rate** and **Max content bytes**.
3. Click **Save and deploy**. The configuration goes to every edge of the project. The new level applies to the next request.

### Set it through the API

```bash
GW=$(curl -s "$ELCHI/api/v3/ai-gateway/gateways/support?project=$PROJECT" -H "Authorization: Bearer $TOKEN" | jq '.data')
BODY=$(echo "$GW" | jq --arg p "$PROJECT" '
  {project: $p, expected_version: .version,
   gateway: (del(.version, .created_at, .updated_at, .updated_by)
             | .capture = {level: "full", retentionDays: 3, sampleRate: 0.25, maxContentBytes: 32768})}')
curl -s -X PUT "$ELCHI/api/v3/ai-gateway/gateways/support" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d "$BODY"
```

What reaches the edges:

```yaml
spec:
  capture:
    recipients: [age1...]        # the project's public key, written by the control plane
  gateways:
    - name: support
      capture: { level: full, retentionDays: 3, sampleRate: 0.25, maxContentBytes: 32768 }
```

## What a row holds

ClickHouse table **`elchi_ai_gateway_requests`**:

| Column | Meaning |
|---|---|
| `ts`, `duration_ms` | Start time and duration of the request. |
| `instance_id`, `project`, `gateway`, `consumer` | Which edge, project, gateway, and consumer (empty on gateways without keys). |
| `provider` | The provider that served (see [Which provider served](#which-provider-served)). |
| `provider_type`, `operation` | The span's provider (`openai`, `aws.bedrock`, …) and operation. |
| `request_model`, `response_model` | The model asked for and the one that answered. |
| `request_id`, `trace_id`, `span_id`, `response_id`, `session_id` | Ids. `trace_id` + `span_id` name one row. |
| `status`, `error_type`, `error_message` | `ok` or `error`. `error_message` holds only "Error code: N". The provider's error body can echo the prompt, so it is stored only inside the encrypted content. |
| `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_creation_tokens`, `reasoning_tokens` | Token breakdown. |
| `finish_reasons` | Finish reasons. |
| `capture_level`, `retention_days` | `metadata` or `full` for this row (a Full gateway's row that was not sampled is `metadata`), and its TTL. |
| `content_enc`, `content_bytes`, `redactions`, `truncated`, `content_recipients` | The encrypted content, its plaintext size, how many values were masked, whether a field was cut, and the public keys it was encrypted to. |

## Content and its encryption

At **Full**, the edge keeps five fields: input messages, output messages, system instructions, tool definitions and the provider's error body. Each field is masked, then truncated, then all five are encrypted together with **age (X25519)** to every key in `spec.capture.recipients`.

- **The key pair is the project's.** The control plane generates it when the project's AI gateway configuration is first saved (the first provider). The public key goes to every edge in `00-providers.yaml`. The private key is stored sealed in the control plane's database and never leaves the control plane.
- **What ClickHouse holds** is ciphertext. Neither ClickHouse operators nor anyone who can read the table can read the content. A Full configuration without recipients is rejected by validation. In Elchi the control plane always writes the recipient.
- **When the project's AI gateway is removed**, its key is kept as a retired key, so content captured earlier stays readable, unless you choose to destroy it (see [Erasing](#erasing)).

### Masking

Before encryption, each field is masked with the gateway's **effective sensitive-data policy** (the project policy plus the gateway's override). See [Sensitive data](https://www.elchi.io/docs/ai-gateway/sensitive-data).

- Every type is masked unless its **Masked in log** is off (`logMask: false`). This includes types whose action in requests is Off.
- The log masks from *unlikely* up. A log masks more than it flags. A rule's **Acts from** can only lower this threshold, so a value the policy flags is never left in the log.
- A masked value becomes `[REDACTED:<type>]`, for example `[REDACTED:email]` or `[REDACTED:credit_card]`. JSON stays valid JSON.
- If a field holds more look-alike values than one scan checks, the whole field becomes `[REDACTED:too_many_matches]`.
- `redactions` counts the masked values.

Older gateways may still carry the superseded `capture.redact` list (`builtin`: `email`, `phone`, `credit_card`, `iban`, `tckn`, `secrets`; `patterns`: extra regexes). It still applies to types whose policy rule says nothing about masking. The gateway page then shows "This gateway still has its own masking list" with a **Follow the policy only** button that clears it.

## Which provider served

For a model that one provider serves, the row names that provider. For a model that **several providers** serve (a pool with weights or fallbacks), Envoy picks the provider after the span starts. The edge then learns from Envoy's access log, on the authorization socket, which provider served:

- A pooled row waits up to **2 seconds** for that log entry, and is checked once more right before its batch is written.
- If no entry comes, `provider` holds the candidates joined with `|` (for example `openai-a|azure-b`). The UI shows "openai-a or azure-b" and, on the request page, "which one served was not recorded".
- Waiting rows are bounded at 4096 rows / 32 MiB. Past that, a row is written at once. At shutdown, waiting rows are flushed.

## Viewing the log

**AI Gateway → Request log**. Only Owners and Admins see the tab. The API refuses other roles.

Filters (they stay for the browser tab's session, so opening a request and coming back keeps the view):

- **Window**: Last 15 minutes, Last 1 hour (default), Last 6 hours, Last 12 hours, Last 24 hours, Last 7 days, Last 30 days. **Refresh** moves the window to now.
- **Gateway**. A gateway whose level is Off is marked "(log off)".
- **Status**: `ok` or `error`.
- **Consumer**, when the project has consumers.
- **Search**: one exact **request, trace, response or session id**.

Columns: Time, Gateway, Consumer, Model, Provider, Status, Tokens (in / out), Duration, Content (**captured** when the row has content). 50 rows per page, newest first.

An empty log explains itself. For example: "No requests in this window: gateway `x` logs nothing (its request log is off)."

### A request's page

Click a row to open `/ai-gateway/requests/<trace>-<span>`:

- **Request**: Provider (with its type), Operation, Consumer ("none (the gateway requires no key)"), Tokens in / out, Cached / reasoning, Finish, Content ("kept, N masked, truncated; kept N days" or "not kept"), Edge, Session, Trace / span, Request id, Response id, Error.
- **Conversation** for a captured row: system instructions, then the input and output messages as a conversation. Masks are highlighted. The page says "Masked on the edge, decrypted for you now. This view is recorded in the audit log."
- **Tool definitions** and **Error body** ("What the provider answered."), when present.
- A row without content says why. For example: "Not captured: gateway `x` keeps the content of 25% of its requests and this one was not sampled.", or "Not captured: gateway `x` logs metadata. Set its request log to full to keep the content."

**Every view that returns content is audited.** The control plane writes an audit entry with action `VIEW_AI_GATEWAY_REQUEST_CONTENT`, the user, the client IP and the request (`<trace>/<span>`), with `content_shown` true or false. The answer carries `Cache-Control: no-store`. The page reads the content once per visit and does not keep it after you leave, so a later visit is read again and audited again.

If the content cannot be opened, the page shows a warning instead. For example: "the content cannot be decrypted: its key was shredded".

### API

```bash
# list (metadata only), newest first
curl -s "$ELCHI/api/v3/ai-gateway/requests?project=$PROJECT&from=2026-12-05T00:00:00Z&gateway=support&status=error&limit=50" \
  -H "Authorization: Bearer $TOKEN"
# {"data":[{"ts":...,"gateway":"support","provider":"openai-a","request_model":"gpt-4o",...,"trace_id":"...","span_id":"..."}],"total":123,"from":...,"to":...}

# one request with its content decrypted (audited)
curl -s "$ELCHI/api/v3/ai-gateway/requests/$TRACE_ID/$SPAN_ID?project=$PROJECT" \
  -H "Authorization: Bearer $TOKEN"
# {"data":{...},"content":{"input_messages":"[...]","output_messages":"[...]","system_instructions":"...","tool_definitions":"...","error_body":"..."}}
# or "content_error":"..." when it cannot be opened
```

List parameters:

- `from` / `to`: RFC 3339. The default window is the last 24 h, the longest 90 days.
- `gateway`, `model`, `status` (`ok` | `error`), `consumer`.
- `search`: an exact request, trace, response or session id. Each id column has its own index.
- `limit`: default 50, at most 500. `offset`.

A row that does not exist (erased, or past its retention) answers `404`.

## Erasing

Erasing deletes rows, metadata and content alike. Only Owners and Admins can erase, and every erasure is audited as `ERASE_AI_GATEWAY_REQUESTS`.

**In the UI**, on a request's page:

- **Erase session**: every request with this `session_id`. Shown when the request has a session id.
- **Erase request**: this request, by its request id. If it has no request id, every request of its trace.

Both ask for confirmation ("It cannot be undone.") and return you to the log.

**Through the API**, give at least one selector. Selectors combine with AND:

```bash
# one session
curl -s -X DELETE "$ELCHI/api/v3/ai-gateway/requests?project=$PROJECT&session_id=$SESSION" -H "Authorization: Bearer $TOKEN"
# one gateway's rows older than a date
curl -s -X DELETE "$ELCHI/api/v3/ai-gateway/requests?project=$PROJECT&gateway=support&before=2026-11-01T00:00:00Z" -H "Authorization: Bearer $TOKEN"
# the project's whole request log
curl -s -X DELETE "$ELCHI/api/v3/ai-gateway/requests?project=$PROJECT&all=true" -H "Authorization: Bearer $TOKEN"
```

Selectors: `session_id`, `request_id`, `trace_id`, `gateway`, `before` (RFC 3339), or `all=true`. A call without any answers `400`.

- The erasure is a ClickHouse lightweight `DELETE`. Rows disappear from reads at once, and ClickHouse removes them from disk in its next merges.
- The hourly rollup `elchi_ai_gateway_requests_1h` holds only counts and latency buckets, no ids or content. Erasing does not change it. See [Usage and costs](https://www.elchi.io/docs/ai-gateway/usage-and-costs#hourly-rollups).
- **Making all captured content unreadable at once:** **AI Gateway → Remove** with **Also destroy the request-log key: captured content can never be read again.** checked, or `DELETE /api/v3/ai-gateway?project=…&shred=true`. This removes the whole AI gateway configuration and destroys every request-log key of the project, retired ones included. Removal is refused while something still uses the AI gateway (the dialog lists what does). See [Operations](https://www.elchi.io/docs/ai-gateway/operations). Rows stay until their TTL, but their content can never be decrypted again.

## Retention

| Data | How long |
|---|---|
| A row of `elchi_ai_gateway_requests` | Its own `retention_days` (the gateway's **Retention (days)** when the row was written; default 7, 1–365). TTL `ts + retention_days`. |
| `elchi_ai_gateway_requests_1h` (counts per hour) | 90 days. |

The usage page's error rate and latency percentiles come from this log, so they cover only gateways that keep one, for their retention.

## Edge settings (config.yaml)

These are the operator's settings on each edge, read once at start. See [Installation](https://www.elchi.io/docs/ai-gateway/installation) for where they live.

```yaml
usage:
  clickhouse_dsn: clickhouse://elchi:<password>@10.0.0.10:19000/elchi   # usage AND request log; empty disables both
requests:
  enabled: true                 # kill switch (default true)
  table: elchi_ai_gateway_requests
  receiver_addr: 127.0.0.1:9003 # must be loopback
  forward:
    endpoint: ""                # optional OTLP/gRPC host:port
    insecure: false
    headers: {}
```

- The request log runs only when `requests.enabled` is true **and** there is a ClickHouse DSN or a forward endpoint. Without either, the extproc is told to export no traces and to capture no content.
- `receiver_addr` must be a loopback address (`127.0.0.1`, `::1` or `localhost`). Any other address stops the service at start: "must be loopback (it receives unredacted content)".

Matching flags and environment variables: `--requests-enabled` / `ELCHI_AI_GATEWAY_REQUESTS_ENABLED`, `--requests-table`, `--requests-receiver-addr`, `--requests-forward-endpoint`, `--requests-forward-insecure`, `--requests-forward-headers` (`k=v,k2=v2`).

## Forwarding to an OTLP endpoint

`requests.forward.endpoint` re-exports the spans to an external OTLP/gRPC collector (Langfuse, Phoenix, Jaeger, an OpenTelemetry collector). TLS 1.2 or later is used unless `insecure: true`. `headers` are sent with every export.

The forward follows the same per-gateway policy:

| Gateway level | Forwarded span |
|---|---|
| Off | Not forwarded. |
| Metadata, or Full but not sampled | Content attributes removed. The status keeps only "Error code: N". |
| Full and sampled | Content **masked and truncated exactly like the stored copy, but NOT encrypted.** |

:::warning[Forwarding Full content leaves it readable]
For a Full gateway, the external endpoint receives the masked prompts and answers **in plain text**. Encryption to the project key protects only the ClickHouse copy. Forward only to a system you trust with that content, over TLS.
:::

A slow or unreachable endpoint never slows requests. Batches queue (256) and are dropped when the queue is full or an export fails within 10 s. Both are counted in `elchi_ai_gateway_requestlog_forward_failures_total`.

## When rows are missing

On the edge, `curl -s 127.0.0.1:9002/metrics | grep requestlog_`:

| Metric | Meaning |
|---|---|
| `elchi_ai_gateway_requestlog_spans_received_total` | GenAI spans the extproc sent. |
| `elchi_ai_gateway_requestlog_spans_dropped_total{reason}` | Spans that became no row:<br/>`capture_off` (the gateway's level is Off)<br/>`no_gateway` (the span had no gateway header)<br/>`unknown_gateway` (not in the applied configuration)<br/>`no_policy` (no configuration applied yet)<br/>`queue_full`<br/>`encrypt_failed` (the row is kept without content)<br/>`duplicate` (a retried export) |
| `elchi_ai_gateway_requestlog_rows_written_total` / `_rows_dropped_total` | ClickHouse writes, and rows lost after retries or a full queue. |
| `elchi_ai_gateway_requestlog_content_captured_total`, `_redactions_total` | Rows with content, and values masked. |

Other causes:

- **No ClickHouse on the control plane:** the API answers `503` "clickhouse not configured; AI gateway request log unavailable".
- **ClickHouse unreachable from the edge:** see [Usage and costs → When ClickHouse is down](https://www.elchi.io/docs/ai-gateway/usage-and-costs#when-clickhouse-is-down).

## Verify it

1. Set a gateway's level to **Full** and save.
2. Send one request through it with an email address in the prompt.
3. Within about a minute, the row appears in **Request log** with **captured**.
4. Open it. The conversation shows the prompt with `[REDACTED:email]`, and the answer.
5. In ClickHouse, `content_enc` of that row does not contain the prompt text.
6. **Erase request**. The request's page then answers "No such request: it was erased or its retention ran out."

Related: [Sensitive data](https://www.elchi.io/docs/ai-gateway/sensitive-data) · [Usage and costs](https://www.elchi.io/docs/ai-gateway/usage-and-costs) · [Security model](https://www.elchi.io/docs/ai-gateway/security-model) · [Ports, files and tables](https://www.elchi.io/docs/ai-gateway/reference/ports-files-and-tables)
