Dev guide :: Observability

Observability with Grafana, Tempo, Loki, and Prometheus

A Codex run took longer than usual. Did the model take longer to respond, did Codex retry a request, or did a shell command stall? Observability uses telemetry emitted during execution to help you answer questions like these after the run has finished.

This guide starts with the three telemetry signals, then walks through collecting them from the native Codex CLI on Windows. You will start a local stack, export one agent turn, and find evidence of that turn in Grafana Explore.

The three signals

SignalWhat it recordsQuestion it answersBackend and query language
TracesTimed operations called spans, grouped by trace ID and linked by parent span IDWhere did this turn spend its time?Tempo and TraceQL
LogsTimestamped events with a message and structured fieldsWhat happened when the request or tool call ran?Loki and LogQL
MetricsNumeric measurements over time, grouped by labelsHow often is this happening, and is it getting worse?Prometheus and PromQL

A trace waterfall shows start times, durations, and nesting. Overlapping spans can represent concurrent work, so adding their durations can overstate elapsed time. In Loki, labels select log streams and filters narrow the records. In Prometheus, a counter tracks a cumulative count, a gauge tracks a value that can rise or fall, and a histogram records a distribution such as request duration.

Keep labels bounded. Environment and service are useful selectors. A trace ID or conversation ID typically has a different value for every run. Keep those IDs in spans or log metadata so they do not create a new metric series or Loki stream for each run.

How the tools work together

OpenTelemetry defines the signals and OTLP defines how they are sent. Codex is the producer. The OpenTelemetry Collector receives and batches its exports, then sends each signal to the matching backend. Grafana queries those backends through configured data sources and turns the results into timelines, log lists, graphs, and dashboards.

flowchart LR
    CLI["Codex CLI on Windows"]
    subgraph LGTM["Grafana LGTM container"]
        Collector["OpenTelemetry Collector"]
        Tempo["Tempo"]
        Loki["Loki"]
        Prom["Prometheus"]
        Grafana["Grafana Explore"]
    end
    CLI -->|"OTLP/HTTP on host port 14318"| Collector
    Collector -->|"Traces"| Tempo
    Collector -->|"Logs"| Loki
    Collector -->|"Metrics via OTLP ingestion"| Prom
    Grafana -->|"TraceQL"| Tempo
    Grafana -->|"LogQL"| Loki
    Grafana -->|"PromQL"| Prom

Prometheus can scrape metrics from HTTP endpoints. In this lab, Codex pushes OTLP to the Collector and the Collector pushes metrics into Prometheus's OTLP receiver. The stack may also show internal component metrics. When checking the lab, look for Codex measurements specifically.

Start the stack on Windows

  1. Install Docker Desktop for Windows from the Docker documentation linked below. Use the WSL 2 backend and start Docker Desktop in Linux containers mode. Wait until the engine is running.
  2. In PowerShell, check that Docker reports a server and that the server OS is linux. Pull the pinned Grafana LGTM image. It bundles Grafana, the Collector, Tempo, Loki, and Prometheus in one local development container.
  3. Start the container and wait for it to report healthy. Open Grafana on port 3300. If prompted to sign in, use admin for both username and password on this disposable local instance.
plaintext
wsl --status
docker version
docker info --format '{{.OSType}}'

docker pull grafana/otel-lgtm:0.40.0
docker run --detach --rm --name codex-observability-guide --env PROMETHEUS_EXTRA_ARGS=--enable-feature=otlp-deltatocumulative --publish 127.0.0.1:3300:3000 --publish 127.0.0.1:14318:4318 grafana/otel-lgtm:0.40.0
docker ps --filter name=codex-observability-guide
docker logs --tail 25 codex-observability-guide
Invoke-RestMethod http://127.0.0.1:3300/api/health

Codex sends some measurements as deltas, which are changes since the previous collection. The Prometheus feature flag converts these into cumulative series on ingestion so you can query the direct Codex metrics.

The left port in each mapping belongs to Windows. Port 3300 opens Grafana in your browser and port 14318 accepts Codex exports. The right port belongs to the container. Publishing to 127.0.0.1 keeps both endpoints on the local machine.

Grafana data source list showing Loki, Prometheus, Pyroscope, and Tempo

Grafana provisions the data sources when the container starts. Select a screenshot to open the viewer, then zoom or drag to inspect details.

Configure Codex

Install the native Windows Codex CLI with npm.cmd install -g @openai/codex if needed, then run codex.cmd login if you have not signed in. The lab uses Codex CLI 0.167.0 and Grafana LGTM 0.40.0. The ordinary model request still uses your configured provider and account.

Back up the user configuration before editing. If the file already has an [otel] section or exporter keys, merge the settings into it and replace the previous exporter definitions. Put these settings in the user configuration file because Codex ignores project-level otel settings.

plaintext
codex.cmd --version
codex.cmd login status
$codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' }
$configPath = Join-Path $codexHome 'config.toml'
if (Test-Path -LiteralPath $configPath) {
    Copy-Item -LiteralPath $configPath -Destination "$configPath.$(Get-Date -Format yyyyMMdd-HHmmss).bak"
}
notepad.exe $configPath
plaintext
[otel]
environment = "observability-lab"
log_user_prompt = false
log_agent_responses = false
log_guardian_assessments = false

[otel.tool_result]
max_bytes = 0

[otel.exporter.otlp-http]
endpoint = "http://127.0.0.1:14318/v1/logs"
protocol = "binary"

[otel.trace_exporter.otlp-http]
endpoint = "http://127.0.0.1:14318/v1/traces"
protocol = "binary"

[otel.metrics_exporter.otlp-http]
endpoint = "http://127.0.0.1:14318/v1/metrics"
protocol = "binary"

The three URLs share one collector address but have different signal paths. Binary means OTLP's protobuf encoding over HTTP. The settings suppress prompt and response text and limit logged tool result text. Telemetry can still carry operation names, paths, account identifiers, host details, and errors. Use a disposable directory and review captures before sharing them.

sequenceDiagram
    participant C as Codex CLI
    participant O as Collector on port 14318
    participant B as Signal backends
    C->>O: POST /v1/traces
    C->>O: POST /v1/logs
    C->>O: POST /v1/metrics
    O->>B: Batch and export each signal
    Note over C,B: Export order can vary

Generate telemetry

Run the smoke test from PowerShell. It creates an empty directory, uses a read-only sandbox, and asks for a predictable answer without requiring a shell tool. Record the start time so you can find the turn in Explore. Let the CLI exit normally so its exporters can flush.

plaintext
$lab = Join-Path ([System.IO.Path]::GetTempPath()) ('codex-observability-' + [guid]::NewGuid())
New-Item -ItemType Directory -Path $lab | Out-Null
Get-Date -Format o
codex.cmd exec --cd $lab --skip-git-repo-check --sandbox read-only --ephemeral --color never 'Reply with exactly OBSERVABILITY_LAB_OK. Do not use tools.'

Expect OBSERVABILITY_LAB_OK in the terminal. That confirms the model turn completed. The three Explore checks below confirm delivery to each telemetry backend.

To compare with a run that attempts a tool call, create one harmless file and run the variant below. If your Windows sandbox blocks the shell command, keep the sandbox enabled. That run gives you a tool failure to investigate alongside the successful smoke test.

plaintext
Set-Content -LiteralPath (Join-Path $lab 'sample.txt') -Value 'observability-lab'
codex.cmd exec --cd $lab --skip-git-repo-check --sandbox read-only --ephemeral --color never 'Read sample.txt with a shell command and return its single line. Do not modify any files.'

Explore traces in Tempo

Open Grafana Explore from the navigation menu and select Tempo. Set the time range to Last 15 minutes, choose the TraceQL editor, and run the query below. Select a trace near the CLI start time to open its waterfall. Expand a span and look at its duration and attributes. If Tempo reports that it pruned the trace, turn off span pruning in the Trace ID query options and run it again.

plaintext
{ span:name = "codex.exec" }

The query finds traces containing the Codex CLI entry span. In this capture, the service appears as Codex Desktop because the CLI inherited the desktop originator. A standalone CLI may use a different service name. The query uses the span name so the service label can vary.

Grafana Explore with a Tempo TraceQL query and a codex.exec result

The Tempo search result gives you the root span name, start time, and duration. Select the trace ID to open the trace.

Grafana Tempo waterfall showing a Codex CLI trace and its child spans

In the waterfall, use the horizontal position and width of each bar to see when the work started and how long it lasted.

Explore logs in Loki

Open a new Explore pane or switch the data source to Loki. Use Code mode and the same time range. Expand a record to see its labels and structured fields. Look for conversation setup and model request events. The tool-call variant may also emit events about the attempted command.

plaintext
{service_name=~".+"} | env="observability-lab" | event_name!="" | line_format "{{.event_name}}"

The stream selector requires a service label. The filters then keep events from the lab environment that have a name. The final stage displays the event name as the line because Codex can put most of the information in structured fields. Inspect fields locally when you need details.

Grafana Explore showing Codex event names returned by Loki

The Loki result lists events such as startup phases, the prompt event, and model transport activity. The screenshot adds a keep stage to show only the service, environment, and event name. The source records retain their fields.

Codex Agent Performance dashboard

Build a Grafana dashboard for the Loki service codex_exec and its codex.tool_result. A result event represents one reported tool call. The dashboard measures calls that produced a result in the selected period.

Use the dashboard to measure completed tool calls and token counts reported by Codex responses. Start with Last 1 hour, or widen the range to include an earlier run.

Run the tool-call example above, then check the following selector in Explore. Set the time range to cover the run and expand a result. The fields used below are tool_name, duration_ms, and success.

plaintext
{service_name="codex_exec"} | event_name="codex.tool_result"

If the local lab uses a different service label, read the service_name value from one result in Explore and use it in every selector. A run without tools does not generate tool results.

Open Dashboards, choose New, New dashboard, and Add visualization, then select Loki. Use Code mode and Instant for each summary panel. Set the Stat panels to Last non-null and choose the units below. Save the dashboard as Codex - Agent Performance.

To load all ten panels at once, download the dashboard JSON and use Dashboards, New, Import. Select your Loki data source when prompted. Save or import the dashboard using a Grafana account with edit access.

Grafana replaces $__range with the dashboard time span. An instant query evaluates the whole selected period once, at its end.

The queries use Loki's native OTLP fields. If your setup writes the fields into logfmt message bodies, add a logfmt parser before filtering those fields. CLI JSON output is separate from OTLP export.

Tool calls

Use Stat with no unit and zero decimals. Count one result per reported call across all streams. An empty period returns zero.

plaintext
sum(count_over_time(
  {service_name="codex_exec"} | event_name="codex.tool_result" [$__range]
)) or vector(0)

Average duration

Use Stat with unit milliseconds. Each numeric duration contributes once, so a stream with one call does not carry the same weight as a stream with ten calls. Missing or invalid durations are excluded. An empty result means there was no usable duration in the period.

plaintext
avg_over_time(
  {service_name="codex_exec"} | event_name="codex.tool_result"
  | duration_ms!="" | unwrap duration_ms | __error__="" [$__range]
) by (service_name)

Failure rate

Use Stat with unit Percent (0–100), one decimal, and threshold steps at 5% and 15%. Divide failed results by all tool results. Codex reports the tool outcome. Pair this panel with the call count because both an empty period and a period with no failures show 0%.

plaintext
(100 * (sum(count_over_time(
  {service_name="codex_exec"} | event_name="codex.tool_result"
  | success="false" [$__range]
)) or vector(0))
/ sum(count_over_time(
  {service_name="codex_exec"} | event_name="codex.tool_result" [$__range]
))) or vector(0)

Calls by tool

Use a Pie chart with an instant query. Under Value options, set Show to All values and use the tool name as the legend. Each tool keeps its reported name, so exec and exec_command appear separately.

plaintext
sort_desc(sum by (tool_name) (count_over_time(
  {service_name="codex_exec"} | event_name="codex.tool_result"
  | tool_name!="" [$__range]
)))
plaintext
{{tool_name}}

Tool calls over time

Use Time series with a Range query and a minimum interval of 1m. Grafana computes the bucket size from the displayed period and panel resolution. Narrow the period to separate nearby calls.

plaintext
sum(count_over_time(
  {service_name="codex_exec"} | event_name="codex.tool_result" [$__interval]
))

Grafana dashboard showing two tool calls, a 249.5 millisecond average, no failures, and one call per tool

Token consumption

Use completed response events. Check that each record represents usage for one response and that it appears once before aggregating across runs or using these totals for billing. Use Stat with no unit and zero decimals for the first four queries.

plaintext
{service_name="codex_exec"} | event_name="codex.sse_event" | event_kind="response.completed"

Input tokens

plaintext
sum(sum_over_time(
  {service_name="codex_exec"} | event_name="codex.sse_event"
  | event_kind="response.completed"
  | unwrap input_token_count | __error__="" [$__range]
)) or vector(0)

Output tokens

plaintext
sum(sum_over_time(
  {service_name="codex_exec"} | event_name="codex.sse_event"
  | event_kind="response.completed"
  | unwrap output_token_count | __error__="" [$__range]
)) or vector(0)

Cached input tokens

plaintext
sum(sum_over_time(
  {service_name="codex_exec"} | event_name="codex.sse_event"
  | event_kind="response.completed"
  | unwrap cached_token_count | __error__="" [$__range]
)) or vector(0)

Total tokens

Add input and output. Cached input is already included in input and reasoning is reported separately in the event details. The sum uses zero for a missing input or output series.

plaintext
(sum(sum_over_time(
  {service_name="codex_exec"} | event_name="codex.sse_event"
  | event_kind="response.completed"
  | unwrap input_token_count | __error__="" [$__range]
)) or vector(0))
+ (sum(sum_over_time(
  {service_name="codex_exec"} | event_name="codex.sse_event"
  | event_kind="response.completed"
  | unwrap output_token_count | __error__="" [$__range]
)) or vector(0))

Input tokens by model

Use Bar chart with an instant query. Add Labels to fields in Columns mode, keeping model, then use Merge series/tables to combine the results. Select model as the category axis. Each bar shows input tokens for one model.

plaintext
sum by (model)(sum_over_time(
  {service_name="codex_exec"} | event_name="codex.sse_event"
  | event_kind="response.completed"
  | model!=""
  | unwrap input_token_count | __error__="" [$__range]
))
plaintext
{{model}}

The three sample responses reported 35,082 input tokens, including 30,976 cached, and 105 output tokens. The total was 35,187 and the cached share of input was 88.3%.

Grafana token totals with an input token bar labeled gpt-6.1-sol

Dashboard diagnostics

If a panel is empty, check the selected time range and service in Explore. Compare the tool and completed response selectors, then count events by type. In Prometheus, run the two Collector queries separately to check whether the stack received and forwarded logs.

plaintext
{service_name="codex_exec"} | event_name="codex.tool_result"
plaintext
{service_name="codex_exec"} | event_name="codex.sse_event" | event_kind="response.completed"
plaintext
sum by (event_name) (count_over_time(
  {service_name="codex_exec"} | event_name!="" [15m]
))
plaintext
sum(otelcol_receiver_accepted_log_records_total)
sum by (exporter) (otelcol_exporter_sent_log_records_total)

The Collector counters describe the pipeline. Use the Loki panels for Codex activity and Tempo for individual traces. Review access and retention for telemetry because event fields can contain commands, results, and account metadata.

Explore metrics in Prometheus

Switch Explore to Prometheus and use Code mode. Start with an instant query to verify that Codex measurements are present. An instant query returns the value at the evaluation time. A range query evaluates over the selected window and is useful when comparing repeated runs.

plaintext
sum(max_over_time(codex_websocket_request_total[15m]))

This example finds the maximum WebSocket request counter value observed in the last 15 minutes for each matching series, then sums those values. The window helps keep a short-lived CLI sample visible after it exits. Use this query to confirm ingestion in the isolated lab. To measure a rate, collect multiple samples from a stable series and apply the rate before aggregating.

Grafana Explore showing an instant Prometheus query with a Codex request counter result

The numeric result confirms that Prometheus received a metric directly from Codex through the Collector.

If your model provider uses another transport, discover the available Codex metric families with the next query. Prometheus normalizes OpenTelemetry names for its default translation strategy. The returned counts represent the number of series per metric name.

plaintext
count by (__name__) (last_over_time({__name__=~"codex_.*"}[15m]))

Investigate a slow run

flowchart TD
    A["Prometheus: spot an unusual duration or error count"]
    B["Tempo: find a trace in that time window"]
    C["Open the waterfall and inspect the longest relevant span"]
    D["Loki: filter matching time and service"]
    E["Compare trace ID or conversation ID when present"]
    A --> B --> C --> D --> E

Start with a narrow time window and the same service across all three data sources. If a log record carries the trace ID, use it to match the exact trace. If it carries a conversation ID instead, compare that field with span attributes where available. Correlation depends on the identifiers emitted with each event. A time and service match can narrow the search when a shared ID is absent.

plaintext
{service_name=~".+"} | env="observability-lab" | trace_id="PASTE_TRACE_ID_HERE" | line_format "{{.event_name}}"

Replace the placeholder with the ID copied from Tempo. A record such as a WebSocket request may have trace context. A completion event can still be useful when you find it by time and conversation ID.

The CLI entry trace in this lab had no matching Loki record. To follow a model event instead, use this Loki query to display the trace IDs attached to WebSocket requests. Copy one result, switch to Tempo, select the Trace ID query type, and run it. This opened separate traces from the same Codex run in the lab.

plaintext
{service_name=~".+"} | env="observability-lab" | event_name="codex.websocket_request" | trace_id!="" | line_format "{{.trace_id}}"

In the captured run, the CLI entry span lasted about 4.12 seconds. The nearby Loki events include a WebSocket request and a first-token timing event. Prometheus also returned a WebSocket request counter value of 2 for the isolated time window. Use the trace to measure the CLI duration and the log fields to examine the individual model events. The counter gives the request count for the matching series, including activity such as connection warm-up.

For a slow turn, inspect whether a model request or a tool operation occupies the relevant part of the waterfall. Then check nearby Loki events for retries, status codes, or a tool error. For a broader comparison, repeat the smoke test and graph a duration or request metric across multiple turns.

Troubleshooting and cleanup

  • If the browser cannot connect, check the container is healthy and the host port is free. If you change the OTLP host port, update all three Codex endpoints.
  • If Codex rejects the TOML, check for duplicate tables and conflicting exporter definitions. Confirm you edited the active user config and that managed policy allows those exporters.
  • If a signal is missing, widen the Explore time range and rerun the smoke test. Verify the data source, endpoint path, and query independently. Internal stack metrics only confirm that the stack itself is reporting.
  • If Tempo and Loki have data but there are no direct Codex metrics, check the metrics exporter URL and the Prometheus delta conversion flag. Tempo's span-derived metrics can be present even when direct OTLP metrics are missing.

Restore your previous OpenTelemetry settings or remove the lab settings from config.toml, then stop the lab container. Docker removes the container because it was started with --rm. The examples use disposable telemetry storage. Remove the temporary sample directory when you are finished.

plaintext
docker stop codex-observability-guide

References

Diagram
100%