UNPKG

@libp2p/prometheus-metrics

Version:

Collect libp2p metrics for scraping by Prometheus or Graphana

54 lines 1.71 kB
import { Gauge } from 'prom-client'; import { normalizeString } from './utils.js'; export class PrometheusMetricGroup { gauge; label; constructor(name, opts) { name = normalizeString(name); const help = normalizeString(opts.help ?? name); const label = this.label = normalizeString(opts.label ?? name); let collect; // calculated metric if (opts?.calculate != null) { collect = async function () { const values = await opts.calculate(); Object.entries(values).forEach(([key, value]) => { this.set({ [label]: key }, value); }); }; } this.gauge = new Gauge({ name, help, labelNames: [this.label], registers: opts.registry !== undefined ? [opts.registry] : undefined, collect }); } update(values) { Object.entries(values).forEach(([key, value]) => { this.gauge.set({ [this.label]: key }, value); }); } increment(values) { Object.entries(values).forEach(([key, value]) => { const inc = typeof value === 'number' ? value : 1; this.gauge.inc({ [this.label]: key }, inc); }); } decrement(values) { Object.entries(values).forEach(([key, value]) => { const dec = typeof value === 'number' ? value : 1; this.gauge.dec({ [this.label]: key }, dec); }); } reset() { this.gauge.reset(); } timer(key) { return this.gauge.startTimer({ [this.label]: key }); } } //# sourceMappingURL=metric-group.js.map