OpenAI Codex Monitoring with OpenTelemetry: Setup and Metrics
Codex OpenTelemetry from a real run: the three [otel] exporter keys, a local Collector, the events Codex emits, per-run metrics, privacy defaults and limits.
Table of Contents
An engineering lead is rolling Codex CLI out to a team of developers (an illustrative scenario). Security asks which shell commands Codex ran, how each was approved and whether prompts leave laptops. The platform team wants tokens and latency per run. Each answer sits in one developer’s terminal scrollback.
Codex OpenTelemetry export fixes that: one [otel] block per developer sends logs, traces and metrics to a Collector you control. A local receiver takes all three, and one real codex exec run on Codex CLI 0.172.0 (2026-11-26, one machine, not a benchmark) shows what arrives, its per-run metrics and where cost data stops.
TL;DR
- Codex OpenTelemetry export uses three separate keys in the [otel] block of ~/.codex/config.toml: exporter for logs, trace_exporter for traces and metrics_exporter for metrics, each with its own OTLP endpoint path.
- A local OpenTelemetry Collector with the OTLP receiver and the debug and file exporters shows what Codex sends before you choose a backend.
- One real codex exec run on Codex CLI 0.172.0 sent 9 log batches, 4 trace batches and 1 metrics batch, with token counts per response, tool results and time to first token.
- The prompt is redacted by default, but tool arguments, an output preview and the signed-in account’s email can reach the log exporter, so treat that pipeline as sensitive.
- Per-turn cost arrives only as an estimate from a background poll every 150 seconds and did not appear in the short run, so token counts are the dependable per-run signal.
Logs, traces and metrics in Codex OpenTelemetry export
OpenAI Codex monitoring with OpenTelemetry starts with three signals that Codex exports on separate switches. Log events carry the prompt length (the text is redacted by default), token counts for each model response, tool decisions and tool results. Traces carry internal spans, metrics carry counters and histograms, and logs and traces stay off until configured.
Logs answer what happened in a run, metrics answer how often and how slow across runs, and traces show internal work and grow fast. OTLP (OpenTelemetry Protocol) export is off by default, per the Codex advanced configuration docs, and codex exec exports too (service codex_exec).
| Signal | Config key | Default | OTLP HTTP path | What this run received |
|---|---|---|---|---|
| Logs | exporter | none | /v1/logs | 9 batches |
| Traces | trace_exporter | none | /v1/traces | 4 batches (1,593 spans) |
| Metrics | metrics_exporter | statsig (follows analytics.enabled) | /v1/metrics | 1 batch (76 instruments, DELTA) |

As of 2026-11-27, Datadog’s OpenAI Codex integration 1.1.0 reads Codex enterprise analytics with an admin key once a day, plus optional per-turn metrics hourly from the Compliance Logs Platform. It does not use Codex’s OpenTelemetry export, so it reads separate data.
A gateway-side audit trail is another layer, covered in governing Codex CLI traffic through an AI gateway, and Codex export starts only once each machine is configured.
Writing the codex otel config block
The codex otel config lives in the [otel] table of your user-level config.toml (~/.codex/config.toml by default), and a project-local config cannot set it. You name an environment, choose whether prompts are logged and add one exporter per signal. Each OTLP HTTP exporter needs its own signal path and a protocol, because the protocol field has no default.
This is the exact capture/config.toml behind the real run, tested end to end with Codex CLI 0.172.0 on 2026-11-26. Its [analytics] enabled = false line turns off OpenAI’s own analytics, and the three OTLP exporters all send to the receiver at 127.0.0.1:4318.
[analytics]
enabled = false
[otel]
environment = "blog-test"
log_user_prompt = false
exporter = { otlp-http = { endpoint = "http://127.0.0.1:4318/v1/logs", protocol = "json" } }
trace_exporter = { otlp-http = { endpoint = "http://127.0.0.1:4318/v1/traces", protocol = "json" } }
metrics_exporter = { otlp-http = { endpoint = "http://127.0.0.1:4318/v1/metrics", protocol = "json" } }
Exporter keys and their defaults
exporter sends logs and trace_exporter sends traces, and both default to none. metrics_exporter defaults to statsig, OpenAI’s own analytics exporter, which follows analytics.enabled. A custom OTLP metrics exporter runs independently of the analytics switch, and only the value “none” turns it off.
Those defaults sit in otel.rs at rust-v0.172.0, which is why a config that sets only exporter gets logs and no traces.
Endpoints, protocol and the gRPC option
An otlp-http exporter takes endpoint, headers, protocol and tls, and protocol is “binary” or “json” with no default. A source comment explains the separate paths: “OTLP HTTP endpoints are signal-specific in our config, so enabling log export must not implicitly send spans to a /v1/logs endpoint.”
The otlp-grpc variant takes endpoint, headers and tls and points at a gRPC port such as 4317 instead. When the Collector needs credentials, the “Refresh collector credentials” section of the OpenAI docs documents a headers_helper setting that supplies them.
Environment and the project-local config rule
environment defaults to “dev” and is exported as the resource attribute env. Our run set it to “blog-test”, and the capture’s resource shows env=blog-test, so one shared Collector can tell a pilot group’s records apart by a single attribute.
A project-local .codex/config.toml cannot set otel: Codex warns “Ignored unsupported project-local config keys” and drops it. Roll the block out through each user’s config.toml or admin-managed config instead, and per the OpenAI docs, administrators can enforce the exporters in requirements.toml.
A local OpenTelemetry Collector for Codex
A local OpenTelemetry Collector shows what Codex sends before you pick a backend. The otelcol-contrib build ships the OTLP receiver, which listens on 4317 for gRPC and 4318 for HTTP, plus a debug exporter that prints records and a file exporter that writes them as JSON.
The OpenTelemetry Collector v0.166.0 release (2026-11-24) ships the file exporter in both the otelcol and otelcol-contrib distributions.
The otelcol-contrib config for a first look
The YAML below routes logs, traces and metrics from the OTLP receiver to the debug and file exporters, with no processors on purpose. It was not executed, because the Collector binary is not installed on the capture machine; the stdlib receiver below stood in.
receivers:
otlp:
protocols:
grpc:
endpoint: localhost:4317
http:
endpoint: localhost:4318
exporters:
debug:
verbosity: detailed
file:
path: ./codex-otlp.json
service:
pipelines:
logs:
receivers: [otlp]
exporters: [debug, file]
traces:
receivers: [otlp]
exporters: [debug, file]
metrics:
receivers: [otlp]
exporters: [debug, file]
The receiver endpoints and their defaults come from the OTLP receiver README.
The debug exporter takes verbosity basic, normal or detailed, and the file exporter needs a path with no default, while its format defaults to json.
The stdlib receiver used for this run
Download the capture file and scripts used in this run (scrubbed capture, scrub.py, config.toml, receiver.py, replay.py, metrics.py and a README with the SHA-256), unzip it, cd codex-otel-capture, then run the commands below.
receiver.py stands in for a Collector’s OTLP receiver plus file exporter, speaking only the JSON form of OTLP/HTTP from the OTLP specification. It accepts POST on the three signal paths, appends each body as a JSON line and returns 415 for protobuf.
import http.server, json, sys, threading
OUT = sys.argv[1]
class H(http.server.BaseHTTPRequestHandler):
def do_POST(self):
n = int(self.headers.get("Content-Length", 0)); body = self.rfile.read(n)
ct = self.headers.get("Content-Type", "")
if "json" not in ct:
self.send_response(415); self.end_headers(); return
with open(OUT, "a") as f:
f.write(json.dumps({"path": self.path, "body": json.loads(body)}) + "\n")
self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(b"{}")
def log_message(self, *a): pass
http.server.ThreadingHTTPServer(("127.0.0.1", 4318), H).serve_forever()
replay.py posts the 14 scrubbed batches back through that receiver, then checks that it wrote identical lines and refused a protobuf body. It is tested end to end, and a diff of metrics.py output on the replayed file and the capture came back empty.
"""Replay capture/otlp.scrubbed.jsonl into capture/receiver.py over OTLP/HTTP JSON, then check
the receiver wrote back the same batches and rejects protobuf with 415. Shows the receiver
path end to end without running Codex.
Usage: python3 replay.py capture/otlp.scrubbed.jsonl <scratch output .jsonl>
"""
import json, os, subprocess, sys, time, urllib.error, urllib.request
src, out = sys.argv[1], sys.argv[2]
here = os.path.dirname(os.path.abspath(__file__))
if os.path.exists(out):
os.remove(out)
srv = subprocess.Popen([sys.executable, os.path.join(here, "capture", "receiver.py"), out])
def post(path, data, ctype):
req = urllib.request.Request("http://127.0.0.1:4318" + path, data=data, headers={"Content-Type": ctype})
try:
return urllib.request.urlopen(req, timeout=10).status
except urllib.error.HTTPError as e:
return e.code
try:
for _ in range(50): # wait for the listener
try:
post("/v1/logs", b"x", "application/x-protobuf"); break
except urllib.error.URLError:
time.sleep(0.1)
sent = [json.loads(l) for l in open(src)]
codes = [post(b["path"], json.dumps(b["body"]).encode(), "application/json") for b in sent]
proto = post("/v1/logs", b"\x0a\x00", "application/x-protobuf")
finally:
srv.terminate(); srv.wait()
got = [json.loads(l) for l in open(out)]
print(f"posted {len(sent)} batches, HTTP codes {sorted(set(codes))}; protobuf POST -> {proto}")
print(f"receiver wrote {len(got)} lines; identical to the source batches: {got == sent}")
assert codes == [200] * len(sent) and proto == 415 and got == sent
$ python3 replay.py capture/otlp.scrubbed.jsonl <scratch>/replayed.jsonl (receiver.py on 127.0.0.1:4318)
posted 14 batches, HTTP codes [200]; protobuf POST -> 415
receiver wrote 14 lines; identical to the source batches: True
Codex OpenTelemetry events from one real exec run
One codex exec run on Codex CLI 0.172.0 sent 9 log batches, 4 trace batches and 1 metrics batch to the local receiver on 2026-11-26. The resource named the service codex_exec with version 0.172.0 and env blog-test. The log events below are what arrived, counted by metrics.py.
The command below ran in a read-only sandbox on a work folder holding two text files, with one prompt that runs ls and head. Codex exited 0, and the receiver kept listening 45 seconds after exit, collecting 14 OTLP batches.
codex exec --skip-git-repo-check -C work "Count the files in this directory with ls, then print the first line of a.txt with head. Report both results in one sentence."
| Name | Signal | What it carries | Seen in this run (count as printed) |
|---|---|---|---|
| codex.conversation_starts | log | session start | yes (1) |
| codex.user_prompt | log | prompt “[REDACTED]” plus prompt_length | yes (1) |
| codex.api_request | log | HTTP request outcome by endpoint | yes (2, both /models) |
| codex.websocket_request | log | WebSocket request outcome | yes (3) |
| codex.sse_event response.completed | log | input, output, cached, reasoning and tool token counts plus ttft_ms | yes (3) |
| codex.turn_ttft | log | time to first token | yes (1) |
| codex.tool_decision | log | decision and source | yes (1) |
| codex.tool_result | log | tool name, success, duration, arguments, output | yes (2) |
| codex.sandbox_outcome | log | denied or escalated outcomes | no (defined in source) |
| codex.turn_cost | log | estimated cost | no (defined in source) |
| codex.tool.call and codex.tool.call.duration_ms | metric | calls by tool and success | yes |
| codex.turn.token_usage | metric | tokens by type | yes |
| codex.turn.e2e_duration_ms and codex.turn.ttft.duration_ms | metric | turn timings | yes |
| codex.api_request (metric) | metric | requests | no (defined in source) |
| codex.turn.cost_microusd | metric | estimated cost | no (defined in source) |
The signal column names where the count was taken (logs), though source also emits several of these events as trace events. Every count comes from one run on one machine, so read them as a sample, not as a benchmark.
Outside the table, the conversation logged codex.startup_phase 8 times and one codex.websocket_connect to /responses, the transport for the turn’s three model requests. Both codex.api_request records were startup fetches to /models, and one more record outside the conversation had no event.name.
Where the event name lives in each log record
The codex.* name sits in the attribute event.name, while the record’s top-level eventName holds the Rust call site, such as “event model-provider/src/models_endpoint.rs:434” on both /models records. A backend filter on eventName misses every Codex event, so metrics.py reads the attribute.
Input, output and tool token counts arrived as strings and cached and reasoning counts as integers, and OTLP JSON may encode 64-bit integers as decimal strings. A parser should accept both forms and reject anything that is not a finite number.
Events defined in source that this run did not emit
codex.turn_cost and codex.sandbox_outcome are defined in source and did not appear. sandbox_outcome reports denied, escalated, timed_out or signal outcomes, and this run had none. One run cannot show why turn_cost was absent, so it stays unexplained.
codex.agent_response and codex.guardian_assessment are opt-in: they need log_agent_responses or log_guardian_assessments (both default false, with a 64 KiB cap) plus an OTLP log exporter. The capture left both settings off, so neither event can appear in its counts.
Turning Codex telemetry into per-run metrics
Codex telemetry gives per-run numbers once you group log events by conversation.id and count tokens, tool calls and time to first token for each run. Logs carry that id and the metric datapoints in this capture did not, so per-run joins come from logs. The table below is the unedited metrics.py output for the captured run.
$ python3 metrics.py --selftest (SYNTHETIC fixture records, not Codex data)
selftest: 18 checks passed on SYNTHETIC fixture records
$ python3 metrics.py capture/otlp.scrubbed.jsonl
OTLP batches by path: /v1/logs 9, /v1/traces 4, /v1/metrics 1
Resource: env=blog-test, service.name=codex_exec, service.version=0.172.0
== (no conversation.id) ==
Log events: (no event.name) 1, codex.api_request 2
HTTP requests (codex.api_request log) to /models: 2, failures 0
== conv-1 ==
Log events: codex.conversation_starts 1, codex.sse_event 3, codex.startup_phase 8, codex.tool_decision 1, codex.tool_result 2, codex.turn_ttft 1, codex.user_prompt 1, codex.websocket_connect 1, codex.websocket_request 3
WebSocket requests (codex.websocket_request log): 3, failures 0
response.completed (codex.sse_event):
# in out cached reason total ttft_ms
1 2 0 0 0 2 -
2 26070 81 13952 0 26151 2616
3 26211 24 25984 0 26235 2114
sum in 52283, out 105, cached 39936, reasoning 0 (tool_token_count is usage.total_tokens, never added to in+out)
codex.turn_ttft duration_ms: [5264]
Tool exec: calls 1, success 1/1, duration_ms [1327]
Tool exec_command: calls 1, success 1/1, duration_ms [224]
Tool decision: exec_command approved (source Config) x1
Trace spans: 1593 (176 distinct names)
Metric instruments: 76 (histogram 47, sum 29); temporality ['DELTA']
codex.turn.token_usage by token_type: cache_write_input 0, cached_input 39936, input 52281, output 105, reasoning_output 0, total 52386
codex.tool.call by tool/success: exec/true 1, exec_command/true 1
codex.turn.e2e_duration_ms: count 1, sum 11127
codex.turn.ttft.duration_ms: count 1, sum 5264
codex.tool.call.duration_ms: count 2, sum 1551
codex.api_request metric present: False
codex.turn.cost_microusd metric present: False

- Requests and failures: codex.websocket_request (3, failures 0); codex.api_request covers HTTP.
- Tokens: codex.sse_event response.completed.
- Time to first token: codex.turn_ttft.
- Tool calls, success and duration: codex.tool_result.
- Approvals and denials: codex.tool_decision.
- Sandbox escalations: codex.sandbox_outcome.
metrics.py fails closed on an empty file, malformed lines, unknown paths, non-numeric or non-finite counts and duplicate records. Its selftest uses synthetic fixture records, and both runs are tested end to end with Python 3.12.5. The list above maps the metrics worth charting to events; conv-1 is the scrubbed conversation id.
"""Per-run table from a Codex OTLP/HTTP JSON capture (one JSON object per line:
{"path": "/v1/logs" | "/v1/traces" | "/v1/metrics", "body": <OTLP JSON>}), as written by
capture/receiver.py. Input: capture/otlp.scrubbed.jsonl (one real `codex exec`
run, Codex CLI 0.172.0, 2026-11-26, one machine; not a benchmark).
Usage:
python3 metrics.py capture/otlp.scrubbed.jsonl
python3 metrics.py --selftest (assert checks on SYNTHETIC fixture records only)
Fails closed: an empty file, a malformed line, an unknown path, a non-numeric or
non-finite count, or a duplicate log record or span raises and exits non-zero.
Never prints user.email, user.account_id, host.name, auth_mode, thread or turn ids.
"""
import json, math, sys
from collections import Counter, defaultdict
PATHS = ("/v1/logs", "/v1/traces", "/v1/metrics")
class CaptureError(ValueError):
pass
def val(v):
"""OTLP AnyValue -> python. OTLP JSON may encode ints as strings."""
for k in ("stringValue", "intValue", "doubleValue", "boolValue"):
if k in v:
return v[k]
return None
def num(v, what):
"""Accept int, float or numeric string (Codex sends some token counts as strings)."""
if isinstance(v, bool) or v is None:
raise CaptureError(f"{what}: not a number: {v!r}")
try:
x = float(v)
except (TypeError, ValueError):
raise CaptureError(f"{what}: not a number: {v!r}")
if not math.isfinite(x):
raise CaptureError(f"{what}: non-finite: {v!r}")
return int(x) if x == int(x) else x
def attrs(o):
return {a["key"]: val(a.get("value", {})) for a in o.get("attributes", [])}
def load(path):
batches = []
with open(path) as f:
for i, line in enumerate(f, 1):
if not line.strip():
continue
try:
d = json.loads(line)
except json.JSONDecodeError as e:
raise CaptureError(f"line {i}: malformed JSON ({e.msg})")
if not isinstance(d, dict) or d.get("path") not in PATHS or not isinstance(d.get("body"), dict):
raise CaptureError(f"line {i}: not a {{path, body}} OTLP batch")
batches.append(d)
if not batches:
raise CaptureError("empty capture: no OTLP batches")
return batches
def analyse(batches):
out = {"batches": Counter(b["path"] for b in batches), "resource": {}}
seen_logs, seen_spans = set(), set()
events = defaultdict(Counter) # conversation -> event.name -> n
responses = defaultdict(list) # conversation -> response.completed rows
tools = defaultdict(lambda: defaultdict(list)) # conversation -> tool -> [(ok, ms)]
decisions = defaultdict(Counter) # conversation -> (tool, decision, source) -> n
api = defaultdict(lambda: defaultdict(lambda: [0, 0])) # conversation -> endpoint -> [requests, failures]
ws = defaultdict(lambda: [0, 0]) # conversation -> [websocket requests, failures]
turn_ttft = defaultdict(list)
spans, span_names = 0, set()
metrics = {}
for b in batches:
body = b["body"]
if b["path"] == "/v1/logs":
for rl in body.get("resourceLogs", []):
ra = attrs(rl.get("resource", {}))
for k in ("service.name", "service.version", "env"):
if k in ra:
out["resource"][k] = ra[k]
for sl in rl.get("scopeLogs", []):
for rec in sl.get("logRecords", []):
key = json.dumps(rec, sort_keys=True)
if key in seen_logs:
raise CaptureError("duplicate log record")
seen_logs.add(key)
a = attrs(rec)
name = a.get("event.name") or "(no event.name)"
conv = a.get("conversation.id") or "(no conversation.id)"
events[conv][name] += 1
if name == "codex.sse_event" and a.get("event.kind") == "response.completed":
row = {k: num(a.get(k), k) for k in (
"input_token_count", "output_token_count", "cached_token_count",
"reasoning_token_count", "tool_token_count")}
row["ttft_ms"] = num(a["ttft_ms"], "ttft_ms") if "ttft_ms" in a else None
responses[conv].append(row)
elif name == "codex.tool_result":
ok = str(a.get("success")).lower() == "true"
tools[conv][a.get("tool_name", "?")].append((ok, num(a.get("duration_ms"), "duration_ms")))
elif name == "codex.tool_decision":
decisions[conv][(a.get("tool_name"), a.get("decision"), a.get("source"))] += 1
elif name == "codex.api_request": # HTTP transport
c = api[conv][a.get("endpoint", "?")]
c[0] += 1
status = num(a["http.response.status_code"], "HTTP status") if "http.response.status_code" in a else None
c[1] += int(status is None or not 200 <= status < 300 or a.get("error.message") is not None)
elif name == "codex.websocket_request": # WebSocket transport
ws[conv][0] += 1
ws[conv][1] += 0 if str(a.get("success")).lower() == "true" else 1
elif name == "codex.turn_ttft":
turn_ttft[conv].append(num(a.get("duration_ms"), "turn_ttft duration_ms"))
elif b["path"] == "/v1/traces":
for rs in body.get("resourceSpans", []):
for ss in rs.get("scopeSpans", []):
for sp in ss.get("spans", []):
sid = (sp.get("traceId"), sp.get("spanId"))
if not sp.get("spanId") or sid in seen_spans:
raise CaptureError("span without id or duplicate span")
seen_spans.add(sid)
spans += 1
span_names.add(sp.get("name"))
else:
for rm in body.get("resourceMetrics", []):
for sm in rm.get("scopeMetrics", []):
for m in sm.get("metrics", []):
kind = next((k for k in ("sum", "histogram", "gauge", "exponentialHistogram") if k in m), None)
if kind is None:
raise CaptureError(f"metric {m.get('name')}: unknown data kind")
t = m[kind].get("aggregationTemporality")
e = metrics.setdefault(m["name"], {"kind": kind, "temporality": set(), "points": []})
e["temporality"].add({1: "DELTA", 2: "CUMULATIVE"}.get(t, "n/a"))
for p in m[kind].get("dataPoints", []):
pa = attrs(p)
if kind == "histogram":
v = (num(p.get("count"), m["name"] + " count"), num(p.get("sum", 0), m["name"] + " sum"))
else:
v = num(p.get("asInt", p.get("asDouble")), m["name"])
e["points"].append((pa, v))
out.update(events=events, responses=responses, tools=tools, decisions=decisions, api=api, ws=ws,
turn_ttft=turn_ttft, spans=spans, span_names=len(span_names), metrics=metrics)
return out
def report(r):
p = print
p("OTLP batches by path: " + ", ".join(f"{k} {r['batches'][k]}" for k in PATHS))
p("Resource: " + ", ".join(f"{k}={v}" for k, v in sorted(r["resource"].items())))
for conv in sorted(r["events"]):
p(f"\n== {conv} ==")
p("Log events: " + ", ".join(f"{n} {c}" for n, c in sorted(r["events"][conv].items())))
for ep, (q, fails) in sorted(r["api"].get(conv, {}).items()):
p(f"HTTP requests (codex.api_request log) to {ep}: {q}, failures {fails}")
if conv in r["ws"]:
q, fails = r["ws"][conv]
p(f"WebSocket requests (codex.websocket_request log): {q}, failures {fails}")
rows = r["responses"].get(conv, [])
if rows:
p("response.completed (codex.sse_event):")
p(f" {'#':>2} {'in':>7} {'out':>5} {'cached':>7} {'reason':>6} {'total':>7} {'ttft_ms':>7}")
for i, x in enumerate(rows, 1):
t = "-" if x["ttft_ms"] is None else x["ttft_ms"]
p(f" {i:>2} {x['input_token_count']:>7} {x['output_token_count']:>5} {x['cached_token_count']:>7}"
f" {x['reasoning_token_count']:>6} {x['tool_token_count']:>7} {t:>7}")
s = lambda k: sum(x[k] for x in rows)
p(f" sum in {s('input_token_count')}, out {s('output_token_count')}, cached {s('cached_token_count')},"
f" reasoning {s('reasoning_token_count')} (tool_token_count is usage.total_tokens, never added to in+out)")
if r["turn_ttft"].get(conv):
p(f"codex.turn_ttft duration_ms: {r['turn_ttft'][conv]}")
for tool, calls in sorted(r["tools"].get(conv, {}).items()):
ok = sum(1 for c in calls if c[0])
p(f"Tool {tool}: calls {len(calls)}, success {ok}/{len(calls)}, duration_ms {[c[1] for c in calls]}")
for (tool, dec, src), n in sorted(r["decisions"].get(conv, {}).items()):
p(f"Tool decision: {tool} {dec} (source {src}) x{n}")
p(f"\nTrace spans: {r['spans']} ({r['span_names']} distinct names)")
m = r["metrics"]
kinds = Counter(e["kind"] for e in m.values())
temps = sorted(set().union(*(e["temporality"] for e in m.values()))) if m else []
p(f"Metric instruments: {len(m)} ({', '.join(f'{k} {n}' for k, n in sorted(kinds.items()))}); temporality {temps}")
if "codex.turn.token_usage" in m:
by = Counter()
for a, v in m["codex.turn.token_usage"]["points"]:
by[a.get("token_type")] += v[1] if isinstance(v, tuple) else v
p("codex.turn.token_usage by token_type: " + ", ".join(f"{k} {v}" for k, v in sorted(by.items())))
if "codex.tool.call" in m:
by = Counter()
for a, v in m["codex.tool.call"]["points"]:
by[(a.get("tool"), a.get("success"))] += v
p("codex.tool.call by tool/success: " + ", ".join(f"{t}/{s} {n}" for (t, s), n in sorted(by.items())))
for name in ("codex.turn.e2e_duration_ms", "codex.turn.ttft.duration_ms", "codex.tool.call.duration_ms"):
if name in m and m[name]["kind"] == "histogram":
c = sum(v[0] for _, v in m[name]["points"]); s = sum(v[1] for _, v in m[name]["points"])
p(f"{name}: count {c}, sum {s}")
for name in ("codex.api_request", "codex.turn.cost_microusd"):
p(f"{name} metric present: {name in m}")
def selftest():
import os, tempfile
kv = lambda k, v: {"key": k, "value": v}
# SYNTHETIC fixture records (not from any Codex run): ints as strings and as numbers, success as string.
sse = {"attributes": [kv("event.name", {"stringValue": "codex.sse_event"}),
kv("event.kind", {"stringValue": "response.completed"}),
kv("conversation.id", {"stringValue": "conv-A"}),
kv("input_token_count", {"stringValue": "100"}),
kv("output_token_count", {"stringValue": "7"}),
kv("cached_token_count", {"intValue": "40"}),
kv("reasoning_token_count", {"intValue": 3}),
kv("tool_token_count", {"stringValue": "107"}),
kv("ttft_ms", {"intValue": "250"})]}
tool = {"attributes": [kv("event.name", {"stringValue": "codex.tool_result"}),
kv("conversation.id", {"stringValue": "conv-A"}),
kv("tool_name", {"stringValue": "exec_command"}),
kv("success", {"stringValue": "false"}),
kv("duration_ms", {"stringValue": "12"})]}
wsr = {"attributes": [kv("event.name", {"stringValue": "codex.websocket_request"}),
kv("conversation.id", {"stringValue": "conv-A"}),
kv("success", {"stringValue": "false"})]}
logs = {"path": "/v1/logs", "body": {"resourceLogs": [{"resource": {"attributes": [kv("env", {"stringValue": "fixture"})]},
"scopeLogs": [{"logRecords": [sse, tool, wsr]}]}]}}
span = {"traceId": "t", "spanId": "s1", "name": "x"}
traces = {"path": "/v1/traces", "body": {"resourceSpans": [{"scopeSpans": [{"spans": [span]}]}]}}
met = {"path": "/v1/metrics", "body": {"resourceMetrics": [{"scopeMetrics": [{"metrics": [
{"name": "codex.turn.token_usage", "histogram": {"aggregationTemporality": 1, "dataPoints": [
{"attributes": [kv("token_type", {"stringValue": "input"})], "count": "1", "sum": 100}]}}]}]}]}}
def run(lines):
fd, p = tempfile.mkstemp(suffix=".jsonl")
with os.fdopen(fd, "w") as f:
f.write("".join(l + "\n" for l in lines))
try:
return analyse(load(p))
finally:
os.remove(p)
checks = [0]
def fails(lines, msg):
checks[0] += 1
try:
run(lines)
except CaptureError as e:
assert msg in str(e), (msg, str(e))
return
raise AssertionError(f"expected failure: {msg}")
r = run([json.dumps(logs), json.dumps(traces), json.dumps(met)])
row = r["responses"]["conv-A"][0]
assert row == {"input_token_count": 100, "output_token_count": 7, "cached_token_count": 40,
"reasoning_token_count": 3, "tool_token_count": 107, "ttft_ms": 250}, row
assert r["tools"]["conv-A"]["exec_command"] == [(False, 12)]
assert r["spans"] == 1 and r["metrics"]["codex.turn.token_usage"]["temporality"] == {"DELTA"}
assert r["resource"] == {"env": "fixture"}
assert r["ws"]["conv-A"] == [1, 1]
checks[0] += 5 # the five assert statements above
for status, error, expected in [(200, None, [1, 0]), ("201", None, [1, 0]),
(503, None, [1, 1]), (302, None, [1, 1]),
(None, "connection failed", [1, 1]), (200, "", [1, 1])]:
http = {"attributes": [kv("event.name", {"stringValue": "codex.api_request"}),
kv("endpoint", {"stringValue": "/models"})]}
if status is not None:
http["attributes"].append(kv("http.response.status_code", {"intValue": status}))
if error is not None:
http["attributes"].append(kv("error.message", {"stringValue": error}))
batch = {"path": "/v1/logs", "body": {"resourceLogs": [{"scopeLogs": [{"logRecords": [http]}]}]}}
assert run([json.dumps(batch)])["api"]["(no conversation.id)"]["/models"] == expected
checks[0] += 1
fails([], "empty capture")
fails(["{not json"], "malformed JSON")
fails([json.dumps({"path": "/v1/other", "body": {}})], "not a {path, body}")
dup = json.loads(json.dumps(logs)); dup["body"]["resourceLogs"][0]["scopeLogs"][0]["logRecords"].append(sse)
fails([json.dumps(dup)], "duplicate log record")
fails([json.dumps(traces), json.dumps(traces)], "duplicate span")
bad = json.loads(json.dumps(logs)); bad["body"]["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]["attributes"][3] = \
kv("input_token_count", {"stringValue": "NaN"})
fails([json.dumps(bad)], "non-finite")
bad["body"]["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]["attributes"][3] = kv("input_token_count", {"stringValue": "abc"})
fails([json.dumps(bad)], "not a number")
print(f"selftest: {checks[0]} checks passed on SYNTHETIC fixture records")
if __name__ == "__main__":
if sys.argv[1:] == ["--selftest"]:
selftest()
elif len(sys.argv) == 2:
try:
report(analyse(load(sys.argv[1])))
except CaptureError as e:
sys.exit(f"capture rejected: {e}")
else:
sys.exit(__doc__)
Token counts per response and per turn
The three response.completed records read 2 in, 0 out with no ttft_ms; 26070 in, 81 out, 13952 cached at 2616 ms; and 26211 in, 24 out, 25984 cached at 2114 ms. They sum to 52283 in, 105 out, 39936 cached and 0 reasoning.
tool_token_count holds usage.total_tokens, so it is the total and is never added to input and output. The codex.turn.token_usage metric reported input 52281, cached_input 39936, output 105 and total 52386, quoted as printed from the metrics batch.
Tool calls, decisions and time to first token
exec ran once, succeeded 1/1 and took 1327 ms; exec_command ran once, succeeded 1/1 and took 224 ms. One codex.tool_decision approved exec_command with source Config. The turn’s codex.turn_ttft was 5264 ms, against response ttft_ms of 2616 and 2114.
The metric side agrees on counts: codex.tool.call shows exec/true 1 and exec_command/true 1, and codex.tool.call.duration_ms shows count 2 with sum 1551. Codex’s own tool_result events carry each tool’s name, arguments and duration, so per-tool latency comes straight from Codex.
For MCP tool latency seen at a gateway, read MCP tool observability for Codex CLI through a gateway.
Metric instruments, DELTA temporality and span volume
The metrics batch held 76 instruments (histogram 47, sum 29), all DELTA. codex.turn.e2e_duration_ms reported count 1, sum 11127, and codex.turn.ttft.duration_ms count 1, sum 5264. The codex.api_request and codex.turn.cost_microusd metrics are defined in source and were not present.
Codex defaults OTLP metrics to delta, and the Codex otel README documents OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=cumulative for backends that need it; see how OpenTelemetry metrics pair with Prometheus.
Traces are the heavy signal: one short prompt produced 1,593 spans with 176 distinct names, mostly internal work. Lead with logs for per-run views, then filter or sample traces at the Collector as in sampling and redacting LLM traces in the OpenTelemetry Collector.
Privacy defaults and turning Codex telemetry off
Codex redacts the prompt text by default and keeps only its length, but a log exporter still receives tool arguments, an output preview and, when the signed-in account has them, the account id and email. Turning telemetry off takes two keys: analytics disabled and metrics_exporter set to none, with log and trace exporters left unset.
That makes the receiving Collector a sensitive system, so scrub captures before you share them. For this post, scrub.py replaced user.email, user.account_id, host.name and conversation.id with fixed values, every UUID with id-1 to id-7, and the workdir path with <scratch>.
What reaches the log exporter by default
log_user_prompt defaults to false, so codex.user_prompt carries “[REDACTED]” and keeps prompt_length, as the capture shows. codex.tool_result log events carry the tool’s arguments and an output preview once a log exporter is set, and a tool_result setting caps the bytes kept.
Log events also carry user.account_id and user.email when the account has them, and trace events never do. So anyone who can query that Collector can tie each tool call, with its arguments, to a named developer’s account and email.
The two switches that stop export
- Set
enabled = falseunder[analytics]to stop OpenAI’s analytics and the default statsig exporter. - Set
metrics_exporter = "none"under[otel], because a custom OTLP metrics exporter runs until then. - Remove
exporterandtrace_exporter, since both default to none. The docs add: “Ifexporter = "none"Codex records events but sends nothing.”
Limits of Codex cost data and short exec runs
Codex emits per-turn cost only as an estimate that a background worker polls for every 150 seconds, and only after the backend marks the turn as priced. The worker runs only with an OTLP log or metrics exporter and never for Amazon Bedrock, so a short run can end before the first poll and some providers report tokens without cost.
The event is codex.turn_cost (usage.estimated_usd, turn.interrupted), beside the counter codex.turn.cost_microusd. The OpenAI provider’s costs come from the OpenAI backend and other providers’ from their own turn-costs endpoint, and a turn not yet Priced is retried, not emitted.
A comment in turn_cost_worker.rs at rust-v0.172.0 states: “Cost telemetry is best effort: auth changes may drop pending turns.”
What the short run showed and what to chart instead
The captured turn took 11127 ms by codex.turn.e2e_duration_ms, and no codex.turn_cost event or codex.turn.cost_microusd metric arrived. The cause is not proven: a short exec run can end before the first 150-second poll, and one run cannot settle it.
Token counts per response and per turn are the dependable per-run signal to chart. Metric datapoints here carry no conversation.id, which matches openai/codex issue #15905, so per-run views join on log events, where every event inside the conversation carried that id.
Per-prompt Codex traces in Future AGI
Future AGI adds a trace-per-prompt view of Codex CLI next to the native OpenTelemetry export. One setup command installs the traceAI Codex plugin, which uses Codex lifecycle hooks rather than the [otel] block, and each prompt becomes one trace with model attempts, token usage, tool spans, subagents and a shared session.
It is a second view, never a replacement, and the [otel] block keeps feeding your Collector. The documented scope is local Codex CLI, not hosted Codex tasks: 0.167.0 on Linux or newer 0.x releases whose hook payloads match, on Node.js 22.16+ in 22.x, or 24.x. Missing cost is not estimated.
Setup and every option are in the Codex CLI integration docs, and the plugin source lives in traceAI on GitHub.
Setup, hook approval and the doctor check
Run setup from your repository in an interactive terminal. It asks for your Future AGI API key and secret key without echoing them and installs @traceai/codex-plugin as a native Codex plugin at user scope. As of 2026-11-27, npm has @traceai/agents 0.1.0 and @traceai/codex-plugin 0.1.1.
npx @traceai/agents setup codex --project coding-agents
npx @traceai/agents doctor codex
Then review the Future AGI hook definitions in Codex /hooks, because setup reports TRUST_REQUIRED until you approve the exact definitions. Restart any open Codex session and run doctor, which checks the configuration, the connection and whether Future AGI accepts your credentials.
Spans per prompt and content capture
Each prompt becomes one trace with a root span named codex, and prompts in one conversation share a session.id. codex.model_attempt spans carry token usage, codex.subagent spans group a delegated child’s calls, tool spans take the tool’s name and codex.compaction spans mark compaction.
Content capture is on by default, redacted on a best-effort basis and capped at 20,000 characters per field. Turn it off with —no-capture-content at setup, FI_AGENT_CAPTURE_CONTENT=false in Codex’s environment or captureContent false in a repository .codex/futureagi.json.
Prompts group into sessions in Future AGI, and each prompt opens as one of the traces in Future AGI.
Answering the Codex rollout review with run data
Back at the rollout review, the lead now answers each question from one run’s telemetry instead of terminal scrollback. Security sees which commands ran, how they were approved and that prompts stay redacted. The platform team gets tokens, time to first token and tool timings per run from the log events.
The rollout plan: ship the [otel] block in each developer’s user config, inspect records in a local Collector before picking a backend, and settle privacy with security before a shared Collector goes live. The metrics.py table goes into the weekly review.
Judging whether each run did good work comes next, in evaluating coding agents once you can see their runs.
Frequently Asked Questions
How do I set up OpenAI Codex OpenTelemetry?
How do I disable Codex telemetry?
Does Codex otel send traces, logs and metrics?
Can I send Codex telemetry to a local OpenTelemetry Collector?
What does Codex CLI telemetry include?
MCP tracing that survives the process boundary: give client and server their own providers, carry traceparent in _meta, and fix split traces and stdio env loss.
Set up an OTel collector for LLM traces: tail sampling that keeps failed and flagged runs, prompt and output redaction, batching, and two OTLP backends.
Track AI agent token usage per LLM call, then roll it up by step, tool call and run with OpenTelemetry attributes, a dated price table and per-run budgets.