Grav v1.14.0

metrics

import "std/sys" (included in import "std") · namespace std.sys

Application metrics written in the Prometheus text format for a /metrics endpoint: counters, gauges and histograms (optionally with labels), plus the process's own memory, CPU time, threads, open files and cycle-collector backlog.

grav
import "std"

fn main() {
    let m = new MetricsRegistry()
    let requests = m.counterVec("http_requests_total", "HTTP requests.", ["method", "status"])
    let inFlight = m.gauge("http_in_flight", "Requests being handled.")
    let latency = m.histogram("http_request_seconds", "Request time.", [0.05, 0.1, 0.5])

    requests.labels("GET", "200").inc()
    requests.labels("GET", "200").inc()
    requests.labels("POST", "201").inc()
    inFlight.inc()
    for (s in [0.02, 0.07, 0.3, 0.9]) { latency.observe(s) }

    print(m.prometheus())
    print("p50 ≈ ${latency.percentile(0.5)}")
}
Output
# HELP http_requests_total HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="GET",status="200"} 2
http_requests_total{method="POST",status="201"} 1
# HELP http_in_flight Requests being handled.
# TYPE http_in_flight gauge
http_in_flight 1
# HELP http_request_seconds Request time.
# TYPE http_request_seconds histogram
http_request_seconds_bucket{le="0.05"} 1
http_request_seconds_bucket{le="0.1"} 2
http_request_seconds_bucket{le="0.5"} 3
http_request_seconds_bucket{le="+Inf"} 4
http_request_seconds_sum 1.29
http_request_seconds_count 4

p50 ≈ 0.1
  • Counters only go up: inc(), add(n). Gauges go both ways: set, add, inc, dec, setToNow(). gaugeFunc(name, help, fn) reads its value from a function each time metrics are written (queue lengths, pool sizes).
  • Histograms count values into buckets by upper bound (Prometheus' default buckets, 5 ms to 10 s, unless you give your own; linearBuckets and exponentialBuckets make them). observe(v), time(body), or startTimer() and observeSince(t) record seconds. percentile(q) estimates a quantile the way Prometheus' histogram_quantile does.
  • Labels: counterVec, gaugeVec and histogramVec take label names. Then labels("GET", "200") is the child for those values, made the first time it is asked for. Keep a child you use on a hot path: labels() takes a lock, and updating a child does not.
  • Process metrics: processMetrics() adds process_resident_memory_bytes, process_virtual_memory_bytes, process_max_resident_memory_bytes, process_cpu_seconds_total, process_threads, process_open_fds, process_max_fds, process_start_time_seconds and grav_gc_pending_roots, all read when written. Metrics.cpuSeconds(), Metrics.threads(), Metrics.openFiles() and Metrics.residentBytes() read them directly.
  • Serving: prometheus() is the text. MetricsRegistry.contentType() is the header to send with it. Metrics.global() is a registry the whole program can share.
  • Updates are lock-free atomics. A counter add is one atomic instruction. A histogram observe is a binary search over the buckets plus three atomic adds. Both are cheap enough for every request.

API

class MetricCounter

A count that only goes up (requests served, errors, bytes sent).

Constructors

  • new MetricCounter()

Methods

  • fn inc()
  • fn add(n: long) — Adds n (n >= 0).
  • fn get() -> long

class MetricGauge

A value that goes up and down (queue length, connections open, temperature).

Constructors

  • new MetricGauge()

Static members

  • static fn of(source: fn() -> double) -> MetricGauge — A gauge read from source whenever metrics are written.

Methods

  • fn set(x: double)
  • fn add(x: double)
  • fn inc()
  • fn dec()
  • fn setToNow() — Sets it to the current unix time (for "last success" gauges).
  • fn get() -> double

class MetricHistogram

How values are spread (request times, sizes): counts in buckets by upper bound, a sum and a count.

Constructors

  • new MetricHistogram(bounds: Array<double>)

Static members

  • static fn defaultBuckets() -> Array<double> — Prometheus' default buckets: 5 ms to 10 s.
  • static fn exponentialBuckets(start: double, factor: double, count: int) -> Array<double> — count buckets from start, each factor times the last.
  • static fn linearBuckets(start: double, width: double, count: int) -> Array<double> — count buckets from start, width apart.

Fields

  • bounds: Array<double> — The bucket upper bounds, rising (+Inf is implied).

Methods

  • fn observe(x: double) — Records one value.
  • fn startTimer() -> long — A start time for observeSince.
  • fn observeSince(startNs: long) — Records the seconds since startTimer().
  • fn time(body: fn()) — Runs body and records how long it took, in seconds.
  • fn count() -> long
  • fn sum() -> double
  • fn bucket(i: int) -> long — Values in bucket i alone (above bounds[i - 1], at or under bounds[i]).
  • fn cumulative(i: int) -> long — Values at or under bounds[i] (cumulative, as Prometheus reports them); i == the number of bounds is +Inf, every value.
  • fn percentile(q: double) -> double — An estimate of the q-quantile (0.5 the median, 0.99 the 99th percentile), interpolated within its bucket as Prometheus' histogram_quantile does.

class MetricFamily

One named metric with its help, type and labelled children.

Constructors

  • new MetricFamily(name: string, help: string, type: string, labelNames: Array<string>, buckets: Array<double>)

Static members

  • static fn num(v: double) -> string

Fields

  • name: string
  • help: string
  • type: string — "counter", "gauge" or "histogram".
  • labelNames: Array<string>

Methods

  • fn counter(values: Array<string>) -> MetricCounter
  • fn gauge(values: Array<string>) -> MetricGauge
  • fn histogram(values: Array<string>) -> MetricHistogram
  • fn setGauge(g: MetricGauge)
  • fn writeTo(sb: StringBuilder) — The family in the Prometheus text format.

class MetricCounterVec

A counter with labels: labels("GET", "200") is the counter for those values.

Constructors

  • new MetricCounterVec(f: MetricFamily)

Methods

  • fn labels(values: Array<string>) -> MetricCounter — The child for these label values, in the order the names were given.
  • fn labels(a: string) -> MetricCounter
  • fn labels(a: string, b: string) -> MetricCounter
  • fn labels(a: string, b: string, c: string) -> MetricCounter
  • fn labels(a: string, b: string, c: string, d: string) -> MetricCounter

class MetricGaugeVec

A gauge with labels.

Constructors

  • new MetricGaugeVec(f: MetricFamily)

Methods

  • fn labels(values: Array<string>) -> MetricGauge — The child for these label values, in the order the names were given.
  • fn labels(a: string) -> MetricGauge
  • fn labels(a: string, b: string) -> MetricGauge
  • fn labels(a: string, b: string, c: string) -> MetricGauge
  • fn labels(a: string, b: string, c: string, d: string) -> MetricGauge

class MetricHistogramVec

A histogram with labels.

Constructors

  • new MetricHistogramVec(f: MetricFamily)

Methods

  • fn labels(values: Array<string>) -> MetricHistogram — The child for these label values, in the order the names were given.
  • fn labels(a: string) -> MetricHistogram
  • fn labels(a: string, b: string) -> MetricHistogram
  • fn labels(a: string, b: string, c: string) -> MetricHistogram
  • fn labels(a: string, b: string, c: string, d: string) -> MetricHistogram

class MetricsRegistry

A set of metrics, written together.

Constructors

  • new MetricsRegistry()

Static members

  • static fn contentType() -> string — The Content-Type a /metrics response should carry.

Methods

  • fn counter(name: string, help: string) -> MetricCounter
  • fn counterVec(name: string, help: string, labelNames: Array<string>) -> MetricCounterVec
  • fn gauge(name: string, help: string) -> MetricGauge
  • fn gaugeVec(name: string, help: string, labelNames: Array<string>) -> MetricGaugeVec
  • fn gaugeFunc(name: string, help: string, source: fn() -> double) -> MetricGauge — A gauge whose value is read from source each time metrics are written.
  • fn histogram(name: string, help: string, buckets: Array<double> = null) -> MetricHistogram — A histogram (the default buckets, 5 ms to 10 s, when buckets is null).
  • fn histogramVec(name: string, help: string, labelNames: Array<string>, buckets: Array<double> = null) -> MetricHistogramVec
  • fn processMetrics() -> MetricsRegistry — Adds the process's own metrics, read when written: resident and virtual memory, CPU seconds, threads, open and maximum file descriptors, start time, and the cycle collector's pending roots.
  • fn prometheus() -> string — Every metric in the Prometheus text format (version 0.0.4), in the order they were registered.
  • fn names() -> Array<string> — The registered metric names.

class Metrics

The process-wide registry, and the process's numbers read directly.

Static members

  • static fn global() -> MetricsRegistry — The registry most applications use.
  • static fn cpuSeconds() -> double — CPU time used so far (user + system), in seconds.
  • static fn threads() -> int — Threads in the process.
  • static fn openFiles() -> int — Open file descriptors.
  • static fn residentBytes() -> long — Resident memory, in bytes.

Edit this page on GitHub