# Request audit events

**Last updated:** 2026-11-27T08:59:34-03:00 (UTC-3)

An audit or billing pipeline needs one record per request, with a shape that does not change between releases: which key called which model, which provider answered, what it cost, how it ended. The `request` log line is meant for people searching logs: it carries few fields, and its shape follows the log. The usage history lives in PostgreSQL, behind the console and the admin API. Neither is a stable stream a collector such as [Vector](https://vector.dev/) can forward as is.

With `logging.request_events: stdout` the gateway writes, for every finished inference request, one JSON line `{"event":"gateway.request","schema_version":1,...}` to its standard output, next to the normal log. The line holds **metadata only**: identifiers, timings, routing, token counts, cost and policy outcomes. It never contains a prompt, an answer, a provider's error message, a request header or a credential.

## How to enable it

```yaml
logging:
  level: info
  request_events: stdout   # default: off
```

| Field | Values | Default | Applied |
| --- | --- | --- | --- |
| `logging.request_events` | `off`, `stdout` | `off` | At startup; restart or roll out to change it |

There is no environment override and no console editor. It is read once at startup because the writer and its queue are built then, and because a pipeline that depends on the stream must not lose it to a runtime edit. Any other value (including `true`, `false`, `Stdout` or `stderr`) stops the boot with `logging.request_events must be off or stdout`.

**Settings & sources → Infrastructure → Request audit events** shows the destination, its source (Default or YAML) and whether this process has the writer. The same data is `infrastructure.logging.request_events` in `GET /api/v1/admin/config`:

```json
"request_events": {"destination": "stdout", "source": "yaml", "default": "off", "restart_required": true, "active": true, "schema_version": 1, "queue_capacity": 4096}
```

`active` is whether this process attached the writer at startup. Neither field proves that a collector receives the lines; watch the metrics [below](#loss-and-back-pressure) for that. At startup, the gateway also logs `request_events_enabled` with `destination`, `source` and `schema_version`.

## Which requests produce an event

Every request that reaches the usage registry: an authenticated call whose key is allowed on the route, on any inference operation (Chat Completions, Messages, Responses, GenerateContent, embeddings, moderations, rerank, images, audio, video, OCR, decisions, Realtime sessions, token counting, containers, vector stores, MCP tool calls and listings, and the other routes that record usage). Each produces exactly one line when it finishes, whatever the outcome: success, provider error, gateway refusal, guardrail block, rate limit, timeout or client disconnect.

These produce none, because they end before the request has a key and an operation: requests without a valid key (401), a key lookup or a team policy or organization that cannot be read (503), an invalid `X-Gateway-End-User` or `X-Gateway-Session-Id` header (400), a key without the route's scope (403 `scope_forbidden`) or a feature its plan does not include; and health checks, `/metrics`, `/v1/models`, the console and the admin API. The `request` log line still records them.

Requests the gateway makes to itself on behalf of a client (batch items, eval runs, the embedding of an auto-routed request, a moderation guardrail, the embeddings and OCR of vector store files) produce their own event with `"internal": true` and the derived request ID, such as `<request_id>.route` or `<request_id>.e0`.

## Schema version 1

Every member is always present. `null` means unknown or not applicable, never zero: a provider that does not report reasoning tokens gives `"reasoning": null`, and a request whose cost cannot be valued gives `"amount": null`, not `"0"`.

| Member | Type | Meaning |
| --- | --- | --- |
| `event` | string | Always `gateway.request`. Use it to tell events from log records. |
| `schema_version` | integer | `1`. A change that removes or renames a member, or changes its type or meaning, increases it. New members can be added within a version. |
| `request_id` | string | The request ID (`X-Request-Id`, also `correlation_id` in logs). |
| `trace_id`, `span_id` | string | The W3C trace and the request's server span, as in the logs and traces. |
| `started_at`, `ended_at` | string | RFC 3339 in UTC, nanosecond precision. `ended_at` is when the answer was complete and its quota settled, before the usage record is written. |
| `duration_ms` | integer | Same value as the usage record and the console's Request logs. |
| `ttfb_ms` | integer or null | Time to the first body byte the gateway wrote (time to first token for streams); null when nothing was written. |
| `method`, `route` | string | HTTP method and route pattern, such as `POST /v1/chat/completions`. |
| `operation` | string | The route's operation: `chat`, `messages`, `responses`, `generate_content`, `embeddings`, `moderations`, `rerank`, `images`, `audio_speech`, `audio_transcriptions`, `video`, `ocr`, `realtime`, `mcp_tools_call`, `mcp_tools_list` and so on. |
| `internal` | boolean | `true` for a call the gateway made to itself on behalf of a client. |
| `requested_model` | string or null | The model name the client sent. Differs from `model` only when the client used a [model alias](/docs/features/model-aliases/). Null when the request was refused before its model was resolved. |
| `model` | string or null | The canonical model that served the request. |
| `auto_route` | string or null | The [auto-routing](/docs/features/auto-routing/) alias the client called, when one chose `model`. |
| `auto_route_choice` | string or null | What that router served: a tier (`simple`, `medium`, `complex`, `reasoning`), a route name, or `default`. |
| `auto_route_reason` | string or null | Why: for the trajectory strategy `signals`, `override`, `hold`, `judge`, `default`, `repeat` or `tier_not_permitted`; the other strategies report their own reasons (`matched`, `complexity`, `classifier` and so on). |
| `auto_route_transition` | string or null | Trajectory strategy with a session: what the request did to the provider's prompt cache, `first`, `kept`, `switched` or `back`. |
| `provider` | string or null | The provider connection ID recorded for the request, as in the usage history: on the routed operations, the target whose answer (success or error) reached the client; on single-connection operations (Realtime, video, token counting, containers, conversations, fine-tuning), the connection chosen before the send. Null when the routed request ended without passing on an answer (refused before dispatch, or the last target failed in transport). |
| `provider_model` | string or null | The upstream model of that target, as configured (`targets[].model`). Null without a send to `provider`, such as a cache hit. |
| `wire_api` | string or null | The OpenAI API `provider_model` was called with: `chat_completions` or `responses`. With [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) it says which one this request used. Set on Chat Completions, Responses, Messages and GenerateContent requests served by an `openai` target; null when `provider_model` is null, for a target of another protocol, and for the other operations (embeddings, images, audio, ...). Added within schema version 1. |
| `attempts` | integer or null | Sends to providers, retries and fallbacks included. Null when nothing was sent: a cache hit, a refusal before dispatch, or an operation that does not count sends. |
| `retries` | integer or null | Sends repeated on the same target ([inference retries](/docs/features/inference-retries/)). |
| `fallbacks` | integer or null | Times the request moved to another target. |
| `status` | integer | The HTTP status the client received; `499` when the client left. |
| `result` | string | `success`, `client_error`, `rate_limited` (429), `blocked` (a guardrail refused the request or the answer), `timeout` (a deadline ended it: `timeout_kind` is set or the status is 504), `client_closed` (499, or a started answer the client stopped reading) or `server_error` (5xx, or a started answer the provider cut or the gateway aborted). |
| `error_code` | string or null | The gateway's own error code when the gateway produced the error (`guardrail_blocked`, `model_forbidden`, `rate_limited`, `circuit_open`, ...). For an answer that had already started and was cut (`truncated` is `true`, `status` is the one the client received): `stream_interrupted` when the provider cut it and `stream_aborted` when the gateway ended it (`result: server_error`), `client_closed_stream` when the client stopped reading (`result: client_closed`). Null on success and when the error body came from the provider: the provider's message can quote the request, so it is never copied. |
| `timeout_kind` | string or null | `first_byte`, `idle`, `max_duration`, `client_stall`, `request` or `attempt` ([timeout controls](/docs/features/stream-timeouts/)). |
| `stream` | boolean | Whether the client asked for a streamed answer. |
| `truncated` | boolean | `true` when an answer had already started (the status was sent) and ended without its end: a stream the provider cut, a client that stopped reading, an administrative stop or an aborted connection. `status` then stays the one the client received, usually `200`, and `result` is not `success`. |
| `cache.hit` | boolean | Whether a gateway cache served the answer. |
| `cache.kind` | string or null | `exact` or `semantic` ([exact cache](/docs/features/exact-cache/), [semantic cache](/docs/features/semantic-cache/)). |
| `tokens.input`, `tokens.output` | integer or null | Tokens the provider reported. |
| `tokens.cache_read` | integer or null | Prompt-cache reads the provider reported (OpenAI `cached_tokens`, Anthropic `cache_read_input_tokens`, Gemini `cachedContentTokenCount`). |
| `tokens.cache_write` | integer or null | Prompt-cache writes: Anthropic `cache_creation_input_tokens`, the `prompt_tokens_details.cache_creation_tokens` of a translated Claude answer (Anthropic or Bedrock), or an OpenAI-compatible `cache_write_tokens`. |
| `tokens.reasoning` | integer or null | Reasoning tokens (OpenAI `reasoning_tokens`, Gemini `thoughtsTokenCount`, the `output_tokens_details.thinking_tokens` of an Anthropic Messages answer), included in `output` by those providers. |
| `cost.state` | string | `known`, `partial` or `unknown`, as in [usage valuation](/docs/features/usage-valuation/). |
| `cost.amount` | string or null | Exact decimal amount when the state is `known`. A string, so no float rounding. |
| `cost.currency` | string or null | `USD` when there is an amount. |
| `cost.reason` | string or null | Why the cost is what it is: `text_token_estimate` for a known cost, otherwise the reason it is unknown (`valuation_disabled` without `usage_valuation`, `rate_unavailable`, `multiple_upstream_attempts`, `non_success_response`, ...). |
| `key_id` | string | The key's ID, never its value. |
| `principal` | string or null | The key's principal. |
| `team` | string or null | The key's team. |
| `organization` | string or null | The team's [organization](/docs/features/organizations/), when `organizations` is on and the PostgreSQL store read its ceiling for this request. |
| `owner` | object or null | `{"kind", "id"}` of the key's [owner](/docs/features/identity-ownership/), under `identity_ownership`. |
| `end_user` | string or null | The end user the client declared (`X-Gateway-End-User` or the body's `user`), under `end_user_tracking`. Caller-declared, not authenticated. |
| `session_id` | string or null | `X-Gateway-Session-Id`, under `session_tracking`. |
| `tags` | object | The request's [usage tags](/docs/features/usage-tags/); `{}` when none. At most eight pairs, the usage tag limit. |
| `guardrails` | array | One entry per guardrail that ran: `{"id", "stage", "outcome", "findings"}`. `stage` is `input` or `output`; `outcome` is `passed`, `masked`, `blocked`, `incomplete` (another guardrail blocked the request first, so this one may not have seen all of the text), `unavailable` (a required check could not run) or `error_allowed` (it failed and its failure mode lets the request through); a `mode: monitor` guardrail (T128) also records `would_block` or `would_mask` (it found something and changed nothing), and has no entry on a request it did not sample ([monitor mode](/docs/features/guardrails/#monitor-mode-try-a-guardrail-before-enforcing-it)). These two values were added within `schema_version` 1: no existing value changed meaning, so a consumer that counts `blocked` stays right, but one that rejects unknown outcomes must accept them; `findings` is a count. Never the matched text. At most 32 entries. |
| `gen_ai` | object | The model call mapped to the [OpenTelemetry GenAI semantic conventions](/docs/features/observability/#genai-semantic-conventions), added within schema version 1 (T052): `operation_name` (`chat`, `embeddings`, `text_completion`, `generate_content`, or the gateway operation where no well-known value applies), `provider_name` (well-known product, such as `openai`, `anthropic`, `aws.bedrock`, `gcp.gemini`, `gcp.vertex_ai`, `azure.ai.openai`), `request_model` (the upstream model of the latest send), `response_model` and `response_id` (only what the provider reported in an answer the gateway did not translate or serve from its cache), `finish_reasons` (array, at most 16, in the provider's order; translated answers carry the canonical reason; `[]` when none was seen; streamed answers need `stream_usage`), `server_address`/`server_port` (host and port of the latest send's connection, never its path or query), `error_type` (the HTTP status the client received as a string when it is 400 or more). Members are null for a request that was not a model call (files, batches, vector stores, containers, conversations, fine-tuning, token counting, stored-response lifecycle calls) or made no send; a cache hit has no `provider_name`, `response_model` or `response_id`. All of `operation_name` through `error_type` are always present. Lines recorded before this release do not have the member. |
| `parameters` | object | What the [request parameter policy](/docs/features/request-parameter-policy/) did to the attempt that answered, by name only: `defaulted`, `overridden`, `capped`, `dropped`, `unsupported_dropped` and `not_applicable` (arrays, empty when nothing applied). Only plain field names (letters, digits, `_ . : -`, up to 64 characters) are listed, at most 32 per list. `unsupported_dropped` comes from the client's own body members, so it lists only known Chat Completions members (`logprobs`, `n`, `service_tier`, ...). `omitted` counts every name left out. |

### Examples

A streamed chat through a model alias, measured against a real provider (one line, wrapped here):

```json
{"event":"gateway.request","schema_version":1,"request_id":"t108-real-stream","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"c8460d20618f472f",
 "started_at":"2026-11-08T08:17:14.402003Z","ended_at":"2026-11-08T08:17:15.767287Z","duration_ms":1365,"ttfb_ms":1330,
 "method":"POST","route":"POST /v1/chat/completions","operation":"chat","internal":false,
 "requested_model":"t108-legacy","model":"t108-chat","auto_route":null,"auto_route_choice":null,"auto_route_reason":null,"auto_route_transition":null,"provider":"openai-real","provider_model":"gpt-4o-mini",
 "attempts":1,"retries":0,"fallbacks":0,"status":200,"result":"success","error_code":null,"timeout_kind":null,"stream":true,"truncated":false,
 "cache":{"hit":false,"kind":null},"tokens":{"input":23,"output":2,"cache_read":0,"cache_write":null,"reasoning":0},
 "cost":{"amount":"0.000004650000000000000000","currency":"USD","state":"known","reason":"text_token_estimate"},
 "key_id":"t108-app","principal":"t108-service","team":"t108-team","organization":"t108-org","owner":null,
 "end_user":"end-user-t108","session_id":"session-t108","tags":{},
 "guardrails":[{"id":"t108-secrets","stage":"input","outcome":"passed","findings":0}],
 "parameters":{"defaulted":[],"overridden":[],"capped":[],"dropped":[],"unsupported_dropped":[],"not_applicable":[],"omitted":0}}
```

A chat request with `reasoning_effort: max` on an [`api: auto`](/docs/features/protocol-translation/#api-auto-the-api-chosen-per-request) target, which the gateway sent to the Responses API, measured against a real provider (abridged):

```json
{"event":"gateway.request","schema_version":1,"request_id":"93e80c107d93260a7a81a2d7b0b1a760","route":"POST /v1/chat/completions","operation":"chat",
 "model":"chat-default","provider":"openai","provider_model":"gpt-6-luna","wire_api":"responses","attempts":1,"status":200,"result":"success",
 "stream":false,"tokens":{"input":12,"output":5,"cache_read":null,"cache_write":null,"reasoning":null}}
```

A request an input guardrail blocked before any provider call (members that stay at their defaults are left out here; the real line has all of them):

```json
{"event":"gateway.request","schema_version":1,"request_id":"t108-real-blocked","status":400,"result":"blocked","error_code":"guardrail_blocked",
 "model":"t108-chat","provider":null,"attempts":null,"tokens":{"input":null,"output":null,"cache_read":null,"cache_write":null,"reasoning":null},
 "cost":{"amount":null,"currency":null,"state":"unknown","reason":"attempt_unobserved"},
 "guardrails":[{"id":"t108-secrets","stage":"input","outcome":"blocked","findings":1}]}
```

The `gen_ai` member of a non-streamed chat answer whose provider asked for a tool, measured with the built gateway and a mock OpenAI-compatible provider (abridged):

```json
{"event":"gateway.request","schema_version":1,"operation":"chat","model":"agent","provider":"mock","provider_model":"mock-model",
 "gen_ai":{"operation_name":"chat","provider_name":"openai","request_model":"mock-model","response_model":"mock-model-2026-01-01",
  "response_id":"chatcmpl-mock1","finish_reasons":["tool_calls"],"server_address":"127.0.0.1","server_port":18452,"error_type":null}}
```

A fallback: the first target refused the connection, the second answered. Two sends, so the valuation is unknown by design:

```json
{"event":"gateway.request","schema_version":1,"request_id":"t108-real-fallback","status":200,"result":"success",
 "model":"t108-fallback","provider":"mock-local","provider_model":"mock-model","attempts":2,"retries":0,"fallbacks":1,
 "cost":{"amount":null,"currency":null,"state":"unknown","reason":"multiple_upstream_attempts"}}
```

## Reading the stream with Vector

The events and the log share stdout, so a collector reads one stream and splits it by the `event` member. Log records never have one (they use `msg`), and every event line starts with `{"event":"gateway.request"`. Each event is written as one whole line: the log and the events go through one serialized writer, so their lines never interleave.

Measured with Vector 0.61.0 reading the gateway's stdout through a pipe (`gateway | vector --config vector.yaml`):

```yaml
# vector.yaml
sources:
  gateway_stdout:
    type: stdin               # or docker_logs / kubernetes_logs for a container
transforms:
  parsed:
    type: remap
    inputs: [gateway_stdout]
    source: |
      parsed, err = parse_json(.message)
      if err != null || !is_object(parsed) { abort }
      . = parsed
  split:
    type: route
    inputs: [parsed]
    route:
      audit: '.event == "gateway.request"'
sinks:
  audit_file:
    type: file                # an S3, HTTP or database sink works the same way
    inputs: [split.audit]
    path: /var/lib/vector/gateway-requests.jsonl
    encoding: {codec: json}
  logs_file:
    type: file
    inputs: [split._unmatched]
    path: /var/lib/vector/gateway-logs.jsonl
    encoding: {codec: json}
```

In Kubernetes, the `kubernetes_logs` source gives each container line in `.message` as well, so the same `remap` and `route` apply. Order events by `ended_at`, not by arrival: a request that writes its usage record takes longer to finish, so a later short request can be written first.

## Loss and back-pressure

The request never waits for its event. The handler copies the metadata into a value and offers it to a bounded in-memory queue of 4,096 events without blocking; one goroutine values, encodes and writes them. When stdout cannot keep up (a stalled collector, a full pipe), the queue fills and new events are **dropped, not delayed**:

- `gateway_request_events_dropped_total{reason="queue_full"}` counts events dropped because the queue was full or already closed;
- `gateway_request_events_dropped_total{reason="write_error"}` counts events that could not be encoded or written;
- `gateway_request_events_written_total` counts events written;
- a `request_events_dropped` warning with the totals and `since_last_warning` is logged at most once every 30 seconds, never per event.

Alert on the rate of the dropped counter. On shutdown the gateway stops taking new events after the HTTP server drains and writes what the queue still holds, for up to 5 seconds; what is still queued then is counted as dropped. The stream is best effort and at most once: there is no disk buffer, no retry and no acknowledgement. The usage history in PostgreSQL (`usage_analytics`) and [durable receipts](/docs/features/durable-usage/) remain the records to reconcile against: the same `request_id` identifies a request in both.

The events roughly double what the gateway writes to stdout, and they share it with the log. The normal log writes synchronously on the request path (`upstream_attempt`, `request` and the others), so a collector that reads stdout slowly already slows requests; with events on, a log record can also wait for an event line being written at that moment. Size the collector for both, and keep stdout on a local pipe or the container runtime's log driver rather than a slow network sink.

## What the event never contains

- No prompt, input, instruction, answer, tool call, file, image, audio or embedding.
- No provider error message or body, no request or response header, no URL query.
- No key value, token, cookie or provider credential: only `key_id`.
- No client-chosen field name except plain parameter names, filtered as described for `parameters`.

`end_user`, `session_id` and `tags` are values the client or the key declares; treat them like the usage history they also appear in ([data inventory](/docs/security/data-inventory/)).

## Limits

- `organization` needs the PostgreSQL store; another identity adapter leaves it null.
- A Chat Completions stream reports tokens only when its usage was asked for: by the client (`stream_options.include_usage`) or by an alias with [`stream_usage: inject`](/docs/features/stream-usage/#ask-for-the-usage-on-the-clients-behalf). Otherwise `tokens` and `cost` stay null for that stream.
- `tokens.reasoning` and `tokens.cache_write` are known only where the provider reports them in the forwarded usage object; a translated provider whose adapter folds them into other counters leaves them null.
- `attempts`, `retries` and `fallbacks` count sends on Chat Completions, Messages, Responses, GenerateContent and the other operations that go through target selection; Realtime, containers, token counting and fine-tuning leave them null.
- `cost` is the same valuation as the usage ledger: it needs `usage_valuation` and a rate ([automatic pricing](/docs/features/automatic-pricing/) or the [price book](/docs/features/pricing/)). It is an advisory estimate, not a charge.

## Upgrade notes

The setting is new and off by default: nothing changes until `logging.request_events: stdout` is set. Before rolling back to an older binary, remove `request_events` from the YAML, because its strict schema refuses the unknown field. A collector that parsed every stdout line as a log record must start filtering on `event` before the setting is turned on.

`wire_api` was added within schema version 1 (T112), as the version rule allows: a collector that maps the event onto a fixed table must accept the new member or ignore unknown ones. No member changed type or meaning.

## See also

- [Logs, traces and metrics](/docs/features/observability/): the `request` line, OTLP export and metrics.
- [Log destinations](/docs/features/observability/#log-destinations): batched delivery of usage records to object storage and HTTP endpoints.
- [Usage valuation](/docs/features/usage-valuation/) and [durable receipts](/docs/features/durable-usage/).
