# Runtime metrics and health snapshot

> The eaxPLC runtime's Prometheus metrics (GET /metrics), the versioned JSON health snapshot served on the PLC's NATS API, and the correlation fields of its structured logs.

Product: eaxPLC · Type: Reference · Editions: Free, Pro, Enterprise
Source: https://eaxware.com/docs/eaxplc/reference/metrics/
Status: migrated page, not yet verified against the current code.

The eaxPLC runtime (`plc-server`, `plc-runtime`) reports its health in two forms that carry the same values:

- **`GET /metrics`**: the Prometheus text format (version 0.0.4), for a Prometheus server or any compatible scraper.
- **`GET /api/metrics/snapshot`**: a compact JSON snapshot with a versioned schema. Like every `/api/` route, it is also served on the PLC's NATS API (`plc.<id>.api`). eaxScada's System Health workspace reads it there, so it needs no HTTP path to the PLC.

Both are in every edition.

Counters count from the runtime's start. They restart at 0 when the runtime restarts; Prometheus `rate()` and `increase()` handle that. Fieldbus device counters also restart when a fieldbus configuration is applied.

## Cost to the scan

Neither endpoint adds work, a lock or an allocation to the scan:

- The values the scan produces are read with atomic loads: the latency histogram, the cycle, overrun and force counts. They are never read under the lock the scan records its statistics with.
- Go runtime values come from `runtime/metrics`, which does not stop the world. `runtime.ReadMemStats`, which does, is not used.

A scrape takes about 70 µs on another goroutine and allocates about 15 KB.

## Access

| Endpoint | Who may call it |
|---|---|
| `GET /metrics` | Any valid session or PLC token: the same rule as `GET /api/stats`. Anonymous only with `--metrics-anonymous-localhost`, and only from the loopback interface. |
| `GET /api/metrics/snapshot` | Any valid session or PLC token, over HTTP or NATS. Never anonymous. |

`/metrics` sits outside `/api/` by Prometheus convention, but the runtime guards it like an `/api/` read. Any other method than `GET` or `HEAD` is refused: `403` below the engineer level, `405` for an engineer.

`--metrics-anonymous-localhost` (off by default) lets a scraper on the same machine read `/metrics` without a token:

- A request whose remote address is not loopback still needs a token.
- A request carrying `X-Forwarded-For` (relayed by a local proxy) still needs a token.
- The option never opens `/api/metrics/snapshot` or any other route.

For a remote Prometheus, mint a token at the lowest role and give it to the scraper as a bearer credential. PLC tokens are valid for 720 hours at most, so renew it before it expires.

```sh
plc-server token mint -user prometheus -role Compliance_Auditor -ttl 720h > /etc/prometheus/eaxplc.token
```

```yaml
scrape_configs:
  - job_name: eaxplc
    scrape_interval: 15s
    authorization:
      type: Bearer
      credentials_file: /etc/prometheus/eaxplc.token
    static_configs:
      - targets: ['plc-01.plant.local:8085']
```

## Prometheus metrics

Every `eaxplc_` series carries the label `plc_id` (`--plc-id`). The other labels are bounded: no tag or user names. Units are seconds and bytes.

### Runtime and scan

| Metric | Type | Labels | Meaning |
|---|---|---|---|
| `eaxplc_build_info` | gauge | `version`, `goversion` | Always 1; the labels carry the build. |
| `eaxplc_start_time_seconds` | gauge | | Unix time the runtime started. |
| `eaxplc_uptime_seconds` | gauge | | Seconds since start. |
| `eaxplc_running` | gauge | | 1 when the PLC scans its program (not stopped, not faulted). |
| `eaxplc_paused` | gauge | | 1 when the PLC is in STOP. |
| `eaxplc_faulted` | gauge | | 1 when a program fault or a watchdog trip put the PLC in STOP. |
| `eaxplc_target_frequency_hz` | gauge | | Target scan frequency. |
| `eaxplc_program_version` | gauge | | Version number of the running program (+1 per deploy since start). |
| `eaxplc_scan_cycles_total` | counter | | Scan cycles run. |
| `eaxplc_scan_overruns_total` | counter | `task` | Cycles longer than 110 % of the period. |
| `eaxplc_watchdog_trips_total` | counter | | Overrun watchdog trips. |
| `eaxplc_scan_duration_seconds` | histogram | `task` | Program execution time per cycle. |
| `eaxplc_scan_jitter_seconds` | histogram | `task` | Period error per cycle: \|actual period − target\|. |
| `eaxplc_scan_jitter_quantile_seconds` | gauge | `task`, `quantile` (0.5, 0.95, 0.99) | Jitter quantiles over the last 10 s. NaN when no cycle ran in the window. |
| `eaxplc_scan_duration_quantile_seconds` | gauge | `task`, `quantile` (0.5, 0.95, 0.99) | Execution time quantiles over the last 10 s. |
| `eaxplc_scan_jitter_max_seconds` | gauge | `task` | Largest jitter since start. |
| `eaxplc_scan_duration_max_seconds` | gauge | `task` | Longest execution since start. |

`task` is `main`: the real-time loop.

The two histograms have buckets at 1, 2, 5, 10, 20, 50, 100, 200 and 500 µs, then 1, 2, 5 and 10 ms. Their `_sum` is exact.

The histograms only grow. `POST /api/stats/latency/reset` clears what `/api/stats/latency` shows, but not these.

The quantile gauges are estimated from the bucket counts of the last 10 s, by linear interpolation inside a bucket. For quantiles over another window, use `histogram_quantile()` on the histograms.

### Cycle recorder (DVR)

| Metric | Type | Meaning |
|---|---|---|
| `eaxplc_dvr_enabled` | gauge | 1 when the recorder is enabled (`--enterprise`). |
| `eaxplc_dvr_recording` | gauge | 1 while it records. |
| `eaxplc_dvr_epoch` | gauge | Cycle counter epoch of the newest recorded cycle: +1 each time the cycle counter restarts. |
| `eaxplc_dvr_recorded_cycles_total` | counter | Cycles recorded. |
| `eaxplc_dvr_lost_cycles_total` | counter | Cycles missing from the recording (gaps). Alert on any increase. |
| `eaxplc_dvr_disk_blocks_dropped_total` | counter | Closed blocks not written to disk because the writer was behind (`--audit-disk`). |
| `eaxplc_dvr_memory_bytes` | gauge | Memory the recording holds. |
| `eaxplc_dvr_memory_limit_bytes` | gauge | Its cap (`--dvr-max-mb`). |
| `eaxplc_dvr_retained_seconds` | gauge | History the recording holds. |
| `eaxplc_telemetry_queue_dropped_total` | counter | Cycles the scan could not queue to the recorder because the queue was full. |
| `eaxplc_websocket_open` | gauge | Telemetry WebSockets (`/api/telemetry`) open now. |
| `eaxplc_websocket_refused_total` | counter | Telemetry WebSockets closed with `1008` by a concurrent socket cap, by `reason`: `per_session` (`--ws-max-per-session`) or `per_ip` (`--ws-max-per-ip`). |

### Operator actions and program changes

| Metric | Type | Labels | Meaning |
|---|---|---|---|
| `eaxplc_forces_active` | gauge | | Forced locations. |
| `eaxplc_writes_total` | counter | `result` | One-shot write requests (`POST /api/write`, over HTTP or NATS). |
| `eaxplc_deploys_total` | counter | `result` (`ok`, `compile_error`) | Program deploys. |
| `eaxplc_rollbacks_total` | counter | `result` (`ok`, `failed`) | Program rollbacks. |

Each result of `eaxplc_writes_total` counts one request, whatever the number of entries in it:

| `result` | Meaning |
|---|---|
| `ok` | Queued for the next scan. |
| `rejected` | Invalid request (400). |
| `denied` | The caller lacks the `plc.write` right (403). |
| `refused_forced` | A target is forced (409). |
| `failed` | Could not be queued. |

Requests refused before authentication (401) are not counted.

### NATS

| Metric | Type | Meaning |
|---|---|---|
| `eaxplc_nats_configured` | gauge | 1 when the runtime serves its API on a broker (`--nats`). |
| `eaxplc_nats_connected` | gauge | 1 while the broker connection is up. |
| `eaxplc_nats_reconnects_total` | counter | Broker reconnections. |

### Fieldbus

There is one series per configured device. The labels are `bus` (bus id), `type` (`modbus_tcp`, `ethernet_ip`, `ethercat`) and `device` (device id). The series exist only when a fieldbus is configured.

| Metric | Type | Meaning |
|---|---|---|
| `eaxplc_fieldbus_device_up` | gauge | 1 while the device exchanges I/O. |
| `eaxplc_fieldbus_cycles_total` | counter | Good I/O cycles. |
| `eaxplc_fieldbus_bad_cycles_total` | counter | Failed I/O cycles that had not yet faulted the device (see below). |
| `eaxplc_fieldbus_faults_total` | counter | Transitions of the device to fault. |
| `eaxplc_fieldbus_last_cycle_seconds` | gauge | Duration of the device's last measured I/O cycle. |

What counts as a bad cycle depends on the bus type:

- **EtherCAT**: no frame came back, or the working counter was wrong.
- **Modbus TCP**: an exception or error answer.
- **EtherNet/IP**: input data more than half the watchdog late.

### Modbus TCP server

These series exist only while the server runs (not with `--no-modbus`).

| Metric | Type | Labels | Meaning |
|---|---|---|---|
| `eaxplc_modbus_server_up` | gauge | | 1 while the server listens. |
| `eaxplc_modbus_server_requests_total` | counter | `kind` (`read`: FC 1–4, `write`: FC 5, 6, 15, 16, `other`) | Requests served. |
| `eaxplc_modbus_server_snapshot_reads_total` | counter | | Of the reads, those answered from the last cycle's copy, without waiting for a scan. |
| `eaxplc_modbus_server_exceptions_total` | counter | | Requests answered with an exception. |
| `eaxplc_modbus_server_connections` | gauge | | Open connections. |
| `eaxplc_modbus_server_connections_total` | counter | | Connections accepted. |

### Go runtime

These use the usual Prometheus Go names, without `plc_id`.

| Metric | Type | Meaning |
|---|---|---|
| `go_info` | gauge | Go version (`version` label). |
| `go_goroutines` | gauge | Goroutines. |
| `go_memstats_heap_alloc_bytes` | gauge | Heap bytes in live and unswept objects. |
| `go_memstats_sys_bytes` | gauge | Memory mapped by the Go runtime. |
| `go_gc_cycles_total` | counter | Completed garbage collections. |
| `go_sched_gomaxprocs_threads` | gauge | GOMAXPROCS. |
| `eaxplc_gc_pause_seconds` | histogram | Stop-the-world GC pauses. The scan stops during them too. |

`eaxplc_gc_pause_seconds` has buckets from 10 µs to 100 ms. It is folded from the runtime's own histogram, so its `_sum` is estimated from bucket midpoints.

## JSON snapshot on the NATS API

The snapshot is the request `GET /api/metrics/snapshot` on the PLC API subject:

| | |
|---|---|
| Subject | `plc.<plc-id>.api` (request/reply) |
| Envelope | `shared/plcapi`: `{"m":"GET","p":"/api/metrics/snapshot","h":{"Authorization":["Bearer "]}}` |
| Reply | `{"s":200,"h":{...},"b":"<base64 JSON body>"}` |
| Over HTTP | `GET /api/metrics/snapshot` with the same credential |

From Go, `plcapi.Do(requester, plcID, plcapi.Request{Method: "GET", Path: "/api/metrics/snapshot", Header: ...}, timeout)` returns the decoded response.

The body is about 1.5 KB with two fieldbus devices.

A caller may send `X-Request-ID` (1 to 64 characters of `A-Z a-z 0-9 . _ : -`). The runtime then logs the request under that id and echoes it in the reply header. Without one, the runtime makes an id: `r-` over HTTP, `n-` over NATS.

### Schema `eaxplc.metrics.v1`

Every field is always present. Adding a field keeps the schema name. A field renamed, removed or changing meaning gives a new name (`eaxplc.metrics.v2`). Readers must ignore fields they do not know.

| Field | Type | Meaning |
|---|---|---|
| `schema` | string | `eaxplc.metrics.v1` |
| `plc_id` | string | `--plc-id` |
| `version` | string | Runtime build version. |
| `ts_ms` | integer | Unix time of the snapshot, ms. |
| `uptime_s` | number | Seconds since start. |
| `scan.state` | string | `running`, `stopped` or `faulted`. |
| `scan.target_hz` | integer | Target scan frequency. |
| `scan.program_version` | integer | Running program's version number. |
| `scan.cycles_total` | integer | Cycles since start. |
| `scan.overruns_total` | integer | Overrun cycles since start. |
| `scan.watchdog_trips_total` | integer | Overrun watchdog trips. |
| `scan.window_s` | number | Length of the quantile window, normally 10 s (shorter just after start). |
| `scan.window_cycles` | integer | Cycles in the window. |
| `scan.jitter_p50_us`, `scan.jitter_p95_us`, `scan.jitter_p99_us` | number or null | Jitter quantiles over the window. Null when no cycle ran in it. |
| `scan.exec_p50_us`, `scan.exec_p99_us` | number or null | Execution time quantiles over the window. |
| `scan.jitter_max_us`, `scan.exec_max_us` | number | Maxima since start. |
| `dvr.enabled`, `dvr.recording` | boolean | Recorder state. |
| `dvr.epoch`, `dvr.last_cycle` | integer | Newest recorded cycle: epoch and cycle number. Together they name a cycle in the DVR timeline. |
| `dvr.recorded_total`, `dvr.lost_total` | integer | Cycles recorded and lost. |
| `dvr.memory_bytes`, `dvr.memory_limit_bytes` | integer | Recording memory and its cap. |
| `dvr.retained_s` | number | History held. |
| `dvr.disk_blocks_dropped_total` | integer | Blocks not written to disk. |
| `forces_active` | integer | Forced locations. |
| `writes.ok`, `.rejected`, `.denied`, `.refused_forced`, `.failed` | integer | One-shot write requests by result. |
| `deploys.ok`, `.failed`, `.rollback_ok`, `.rollback_failed` | integer | Deploys and rollbacks by result. |
| `nats.configured`, `nats.connected` | boolean | Broker connection. |
| `nats.reconnects_total` | integer | Broker reconnections. |
| `fieldbus[]` | array | One entry per bus, its devices summed. Empty when no fieldbus is configured. |
| `fieldbus[].bus`, `.type` | string | Bus id and type. |
| `fieldbus[].devices`, `.healthy` | integer | Devices, and those exchanging I/O. |
| `fieldbus[].cycles_total`, `.bad_cycles_total`, `.faults_total` | integer | Good and bad I/O cycles, transitions to fault. |
| `fieldbus[].last_cycle_max_us` | number | Longest last-measured I/O cycle among the devices. |
| `modbus_server` | object or null | Null when the Modbus TCP server is off. |
| `modbus_server.read_requests_total`, `.write_requests_total`, `.other_requests_total`, `.exceptions_total` | integer | Requests by class, and exceptions. |
| `modbus_server.snapshot_read_requests_total` | integer | Of `read_requests_total`, the reads answered from the last cycle's copy, without waiting for a scan. |
| `modbus_server.connections` | integer | Open connections. |
| `go.goroutines`, `go.heap_bytes`, `go.total_bytes`, `go.gc_cycles_total` | integer | Go runtime. |
| `go.gc_pause_max_us` | number | Upper bound of the largest GC pause bucket reached since start. |
| `telemetry.queue_dropped_total` | integer | Cycles not queued to the recorder. |
| `telemetry.ws_open`, `telemetry.ws_refused_per_session_total`, `telemetry.ws_refused_per_ip_total` | integer | Telemetry WebSockets open, and refused by each socket cap since start. |

Example (`plc-server`, two fieldbus devices not reachable):

```json
{
  "schema": "eaxplc.metrics.v1", "plc_id": "obs-test", "version": "0.0.0-dev",
  "ts_ms": 1790922524585, "uptime_s": 60.35,
  "scan": {"state": "running", "target_hz": 1000, "program_version": 1, "cycles_total": 60158,
           "overruns_total": 27, "watchdog_trips_total": 0, "window_s": 10.95, "window_cycles": 10949,
           "jitter_p50_us": 0.52, "jitter_p95_us": 0.98, "jitter_p99_us": 4.96,
           "exec_p50_us": 3.05, "exec_p99_us": 8.98, "jitter_max_us": 1557.3, "exec_max_us": 421.7},
  "dvr": {"enabled": true, "recording": true, "epoch": 0, "last_cycle": 60158, "recorded_total": 60158,
          "lost_total": 0, "memory_bytes": 1120240, "memory_limit_bytes": 268435456, "retained_s": 60.16,
          "disk_blocks_dropped_total": 0},
  "forces_active": 0,
  "writes": {"ok": 0, "rejected": 0, "denied": 0, "refused_forced": 0, "failed": 0},
  "deploys": {"ok": 0, "failed": 0, "rollback_ok": 0, "rollback_failed": 0},
  "nats": {"configured": false, "connected": false, "reconnects_total": 0},
  "fieldbus": [
    {"bus": "mb-plant", "type": "modbus_tcp", "devices": 1, "healthy": 0, "cycles_total": 0,
     "bad_cycles_total": 0, "faults_total": 11, "last_cycle_max_us": 0},
    {"bus": "eip-drives", "type": "ethernet_ip", "devices": 1, "healthy": 0, "cycles_total": 0,
     "bad_cycles_total": 0, "faults_total": 0, "last_cycle_max_us": 0}
  ],
  "modbus_server": {"read_requests_total": 0, "snapshot_read_requests_total": 0, "write_requests_total": 0, "other_requests_total": 0,
                    "exceptions_total": 0, "connections": 0},
  "go": {"goroutines": 52, "heap_bytes": 3738648, "total_bytes": 14585856, "gc_cycles_total": 3, "gc_pause_max_us": 0.064},
  "telemetry": {"queue_dropped_total": 0, "ws_open": 1, "ws_refused_per_session_total": 0, "ws_refused_per_ip_total": 0}
}
```

## Structured logs

The runtime logs through one structured logger, Go's `log/slog`:

- **Console** (stderr): text by default, or JSON lines with `--log-format json` (for a container log collector).
- **Log file**: always JSON lines. `plc-server` writes `logs/eaxPLC.log` and `plc-runtime` writes `logs/eaxPLC-rt.log`. The file rotates at 20 MB and five files are kept.
- **Level**: `--log-level debug|info|warn|error` (default `info`).

Every line carries `time`, `level`, `msg`, `plc_id` and `component`. The components are `main`, `runtime`, `http`, `deploy`, `executor`, `codestore`, `gitstore`, `nats`, `fieldbus`, `watchdog`, `auth`, `dvr`, `modbus`, `opcua`, `uns`, `telemetry`, `eaxtags`, `attach` and `metrics`.

These correlation fields are added where they apply:

| Field | Where |
|---|---|
| `request_id` | Lines logged for an API request, over HTTP or NATS: deploys, rollbacks, fieldbus changes, authentication errors. The same id is in the `X-Request-ID` response header. |
| `deploy_id` | Deploy and rollback lines. It is also returned in the deploy or rollback response (`deploy_id`). |
| `cycle`, `dvr_epoch` | Program swaps, scan faults and watchdog trips. They name the cycle in the DVR timeline. |
| `audit_seq` | Lines saying that an audit record was written. The log refers to the audit record by its sequence number and never copies its content. |

The logger never writes secrets:

- Attributes whose name means a secret are replaced by `[REDACTED]`: token, password, secret, signature, seed, NKey, authorization, cookie, API key.
- Free text is scrubbed before it is written: messages, errors, URLs and JSON bodies. The scrubber removes PLC tokens (`v1.…`), JWTs, NKey seeds, `Bearer` credentials, `user:password@` in URLs and secret query parameters.
