bare-prom-client
Client for prometheus
bare-prom-client — Client for prometheus.
npm i bare-prom-clientUsage
See example folder for a sample usage. The library does not bundle any web
framework. To expose the metrics, respond to Prometheus's scrape requests with
the result of await registry.metrics().
Usage with Node.js's cluster module
Node.js's cluster module spawns multiple processes and hands off socket
connections to those workers. Returning metrics from a worker's local registry
will only reveal that individual worker's metrics, which is generally
undesirable. To solve this, you can aggregate all of the workers' metrics in the
master process. See example/cluster.js for an example.
Default metrics use sensible aggregation methods. (Note, however, that the event
loop lag mean and percentiles are averaged, which is not perfectly accurate.)
Custom metrics are summed across workers by default. To use a different
aggregation method, set the aggregator property in the metric config to one of
'sum', 'first', 'min', 'max', 'average' or 'omit'. (See lib/metrics/version.js
for an example.)
If you need to expose metrics about an individual worker, you can include a
value that is unique to the worker (such as the worker ID or process ID) in a
label. (See example/server.js for an example using
worker_${cluster.worker.id} as a label value.)
Metrics are aggregated from the global registry by default. To use a different
registry, call
client.AggregatorRegistry.setRegistries(registryOrArrayOfRegistries) from the
worker processes.
API
Registry
clear(): void
Source
Remove all metrics from the registry
contentType: BoundRegistryContentType
Source
Gets the Content-Type of the metrics for use in the response headers.
getMetricsAsArray(): MetricObject[]
Source
Get all metrics as objects
Returns MetricObject[] — All registered metrics as plain objects.
getMetricsAsJSON(): Promise<MetricObjectWithValues<MetricValue<string>>[]>
Source
Get all metrics as objects
Returns Promise<MetricObjectWithValues<MetricValue<string>>[]> — A promise resolving to all registered metrics as objects, each with its current values.
getSingleMetric<T extends string>(name: string): Metric<T> | undefined
Source
Get a single metric
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The name of the metric |
Returns Metric<T> | undefined — The registered metric named name, or undefined if none is registered.
getSingleMetricAsString(name: string): Promise<string>
Source
Get a string representation of a single metric by name
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The name of the metric |
Returns Promise<string> — A promise resolving to the exposition-format string for the named metric.
metrics(): Promise<string>
Source
Get string representation for all metrics
Returns Promise<string> — A promise resolving to the exposition-format string for all registered metrics.
registerMetric<T extends string>(metric: Metric<T>): void
Source
Register metric to register
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
metric | Metric<T> | — | Metric to add to register |
Registry.merge(registers: Registry[]): Registry
Source
Merge registers
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
registers | Registry[] | — | The registers you want to merge together |
Returns Registry — A new Registry containing the metrics of every registry in registers.
Registry.OPENMETRICS_CONTENT_TYPE: OpenMetricsContentType
Source
HTTP OpenMetrics Content-Type for metrics response headers.
Registry.PROMETHEUS_CONTENT_TYPE: PrometheusContentType
Source
HTTP Prometheus Content-Type for metrics response headers.
removeSingleMetric(name: string): void
Source
Remove a single metric
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The name of the metric to remove |
resetMetrics(): void
Source
Reset all metrics in the registry
setContentType(contentType: BoundRegistryContentType): void
Source
Set the content type of a registry. Used to change between Prometheus and OpenMetrics versions.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
contentType | BoundRegistryContentType | — | The type of the registry |
setDefaultLabels(labels: object): void
Source
Set static labels to every metric emitted by this registry
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels | object | — | of name/value pairs: |
| { defaultLabel: "value", anotherLabel: "value 2" } |
AggregatorRegistry
AggregatorRegistry.aggregate
AggregatorRegistry.aggregate<T extends RegistryContentType>(metricsArr: Array<object>): Registry<T>Creates a new Registry instance from an array of metrics that were
created by registry.getMetricsAsJSON(). Metrics are aggregated using
the method specified by their aggregator property, or by summation if
aggregator is undefined.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
metricsArr | Array<object> | — | Array of metrics, each of which created by |
registry.getMetricsAsJSON(). |
Returns Registry<T> — aggregated registry.
AggregatorRegistry.setRegistries
AggregatorRegistry.setRegistries(regs: | Array<
Registry<PrometheusContentType> | Registry<OpenMetricsContentType>
>
| Registry<PrometheusContentType>
| Registry<OpenMetricsContentType>): voidSets the registry or registries to be aggregated. Call from workers to use a registry/registries other than the default global registry.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
regs | | Array< Registry<PrometheusContentType> | Registry<OpenMetricsContentType> > | Registry<PrometheusContentType> | Registry<OpenMetricsContentType> | — | Registry or registries to be |
| aggregated. |
clusterMetrics(): Promise<string>
Source
Gets aggregated metrics for all workers.
Returns Promise<string> — Promise that resolves with the aggregated
metrics.
Counter
new Counter(configuration: CounterConfiguration<T>)
Source
Counters go up, and reset when the process restarts.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
configuration | CounterConfiguration<T> | — | Configuration when creating a Counter metric. Name and Help is required. |
Counter.Internal
interface Internal {
/**
* Increment with value
* @param value The value to increment with
*/
inc(value?: number): void;
}Counter.get(): Promise<MetricObjectWithValues<MetricValue<T>>>
Source
Get counter metric object
Returns Promise<MetricObjectWithValues<MetricValue<T>>> — A promise resolving to the counter's current value as a metric object.
Counter.inc(labels: LabelValues<T>, value?: number): void
Source
Increment for given labels
Overloads:
inc(labels: LabelValues<T>, value?: number): void
inc(value?: number): void
inc(incData: IncreaseDataWithExemplar<T>): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels | LabelValues<T> | — | Object with label keys and values |
value? | number | — | The number to increment with |
labels(...values: string[]): Counter.Internal
Source
Return the child for given labels
Overloads:
labels(...values: string[]): Counter.Internal
labels(labels: LabelValues<T>): Counter.InternalParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
values | string[] | — | Label values |
Returns Counter.Internal — Configured counter with given labels
Counter.remove(...values: string[]): void
Source
Remove metrics for the given label values
Overloads:
remove(...values: string[]): void
remove(labels: LabelValues<T>): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
values | string[] | — | Label values |
Counter.reset(): void
Source
Reset counter values
Gauge
new Gauge(configuration: GaugeConfiguration<T>)
Source
Gauges are similar to Counters but a Gauge's value can be decreased.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
configuration | GaugeConfiguration<T> | — | Configuration when creating a Gauge metric. Name and Help is mandatory |
dec(labels: LabelValues<T>, value?: number): void
Source
Decrement gauge
Overloads:
dec(labels: LabelValues<T>, value?: number): void
dec(value?: number): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels | LabelValues<T> | — | Object with label keys and values |
value? | number | — | Value to decrement with |
Gauge.Internal
interface Internal<T extends string> {
/**
* Increment gauge with value
* @param value The value to increment with
*/
inc(value?: number): void;
/**
* Decrement with value
* @param value The value to decrement with
*/
dec(value?: number): void;
/**
* Set gauges value
* @param value The value to set
*/
set(value: number): void;
/**
* Set gauge value to current epoch time in ms
*/
setToCurrentTime(): void;
/**
* Start a timer. Calling the returned function will set the gauge's value
* to the observed duration in seconds.
* @return Function to invoke when timer should be stopped. The value it
* returns is the timed duration.
*/
startTimer(): (labels?: LabelValues<T>) => number;
}Gauge.get(): Promise<MetricObjectWithValues<MetricValue<T>>>
Source
Get gauge metric object
Returns Promise<MetricObjectWithValues<MetricValue<T>>> — A promise resolving to the gauge's current value as a metric object.
Gauge.inc(labels: LabelValues<T>, value?: number): void
Source
Increment gauge for given labels
Overloads:
inc(labels: LabelValues<T>, value?: number): void
inc(value?: number): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels | LabelValues<T> | — | Object with label keys and values |
value? | number | — | The value to increment with |
labels(...values: string[]): Gauge.Internal<T>
Source
Return the child for given labels
Overloads:
labels(...values: string[]): Gauge.Internal<T>
labels(labels: LabelValues<T>): Gauge.Internal<T>Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
values | string[] | — | Label values |
Returns Gauge.Internal<T> — Configured gauge with given labels
Gauge.remove(...values: string[]): void
Source
Remove metrics for the given label values
Overloads:
remove(...values: string[]): void
remove(labels: LabelValues<T>): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
values | string[] | — | Label values |
Gauge.reset(): void
Source
Reset gauge values
set(labels: LabelValues<T>, value: number): void
Source
Set gauge value for labels
Overloads:
set(labels: LabelValues<T>, value: number): void
set(value: number): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels | LabelValues<T> | — | Object with label keys and values |
value | number | — | The value to set |
setToCurrentTime(labels?: LabelValues<T>): void
Source
Set gauge value to current epoch time in seconds
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels? | LabelValues<T> | — | Object with label keys and values |
Gauge.startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number
Source
Start a timer. Calling the returned function will set the gauge's value to the observed duration in seconds.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels? | LabelValues<T> | — | Object with label keys and values |
Returns (labels?: LabelValues<T>) => number — Function to invoke when timer should be stopped. The value it
returns is the timed duration.
Histogram
new Histogram(configuration: HistogramConfiguration<T>)
Source
Histograms track sizes and frequency of events.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
configuration | HistogramConfiguration<T> | — | Configuration when creating the Histogram. Name and Help is mandatory |
Histogram.get(): Promise<MetricObjectWithValues<MetricValueWithName<T>>>
Source
Get histogram metric object
Returns Promise<MetricObjectWithValues<MetricValueWithName<T>>> — A promise resolving to the histogram's current buckets and counts as a metric object.
Histogram.Config
interface Config {
/**
* Buckets used in the histogram
*/
buckets?: number[];
}Histogram.Internal
interface Internal<T extends string> {
/**
* Observe value
* @param value The value to observe
*/
observe(value: number): void;
/**
* Start a timer. Calling the returned function will observe the
* duration in seconds in the histogram.
* @param labels Object with label keys and values
* @return Function to invoke when timer should be stopped. The value it
* returns is the timed duration.
*/
startTimer(): (labels?: LabelValues<T>) => void;
}labels(...values: string[]): Histogram.Internal<T>
Source
Return the child for given labels
Overloads:
labels(...values: string[]): Histogram.Internal<T>
labels(labels: LabelValues<T>): Histogram.Internal<T>Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
values | string[] | — | Label values |
Returns Histogram.Internal<T> — Configured histogram with given labels
Histogram.observe(value: number): void
Source
Observe value
Overloads:
observe(value: number): void
observe(labels: LabelValues<T>, value: number): void
observe(observeData: ObserveDataWithExemplar<T>): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
value | number | — | The value to observe |
Histogram.remove(...values: string[]): void
Source
Remove metrics for the given label values
Overloads:
remove(...values: string[]): void
remove(labels: LabelValues<T>): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
values | string[] | — | Label values |
Histogram.reset(): void
Source
Reset histogram values
Histogram.startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number
Source
Start a timer. Calling the returned function will observe the duration in seconds in the histogram.
Overloads:
startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number
startTimer(labels?: LabelValues<T>, exemplarLabels?: LabelValues<T>): (labels?: LabelValues<T>, exemplarLabels?: LabelValues<T>) => numberParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels? | LabelValues<T> | — | Object with label keys and values |
Returns (labels?: LabelValues<T>) => number — Function to invoke when timer should be stopped. The value it
returns is the timed duration.
zero(labels: LabelValues<T>): void
Source
Initialize the metrics for the given combination of labels to zero
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels | LabelValues<T> | — | Object with label keys and values to initialize to zero. |
Summary
new Summary(configuration: SummaryConfiguration<T>)
Source
Summaries calculate percentiles of observed values.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
configuration | SummaryConfiguration<T> | — | Configuration when creating Summary metric. Name and Help is mandatory |
Summary.get(): Promise<MetricObjectWithValues<MetricValueWithName<T>>>
Source
Get summary metric object
Returns Promise<MetricObjectWithValues<MetricValueWithName<T>>> — A promise resolving to the summary's current percentiles as a metric object.
labels(...values: string[]): Summary.Internal<T>
Source
Return the child for given labels
Overloads:
labels(...values: string[]): Summary.Internal<T>
labels(labels: LabelValues<T>): Summary.Internal<T>Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
values | string[] | — | Label values |
Returns Summary.Internal<T> — Configured summary with given labels
Summary.observe(value: number): void
Source
Observe value in summary
Overloads:
observe(value: number): void
observe(labels: LabelValues<T>, value: number): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
value | number | — | The value to observe |
Summary.remove(...values: string[]): void
Source
Remove metrics for the given label values
Overloads:
remove(...values: string[]): void
remove(labels: LabelValues<T>): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
values | string[] | — | Label values |
Summary.reset(): void
Source
Reset all values in the summary
Summary.startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number
Source
Start a timer. Calling the returned function will observe the duration in seconds in the summary.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
labels? | LabelValues<T> | — | Object with label keys and values |
Returns (labels?: LabelValues<T>) => number — Function to invoke when timer should be stopped
Summary.Config
interface Config {
/**
* Configurable percentiles, values should never be greater than 1
*/
percentiles?: number[];
}Summary.Internal
interface Internal<T extends string> {
/**
* Observe value in summary
* @param value The value to observe
*/
observe(value: number): void;
/**
* Start a timer. Calling the returned function will observe the
* duration in seconds in the summary.
* @param labels Object with label keys and values
* @return Function to invoke when timer should be stopped. The value it
* returns is the timed duration.
*/
startTimer(): (labels?: LabelValues<T>) => number;
}Pushgateway
new Pushgateway(url: string, options?: any, registry?: Registry<T>)
Source
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
url | string | — | Complete url to the Pushgateway. If port is needed append url with :port |
options? | any | — | Options |
registry? | Registry<T> | — | Registry |
delete(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>
Source
Delete all metrics for jobName
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
params | Pushgateway.Parameters | — | Push parameters |
Returns Promise<{ resp?: unknown; body?: unknown }> — A promise resolving with the Pushgateway HTTP response and body.
push(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>
Source
Overwrite all metric (using PUT to Pushgateway)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
params | Pushgateway.Parameters | — | Push parameters |
Returns Promise<{ resp?: unknown; body?: unknown }> — A promise resolving with the Pushgateway HTTP response and body.
pushAdd(params: Pushgateway.Parameters): Promise<{ resp?: unknown; body?: unknown }>
Source
Add metric and overwrite old ones
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
params | Pushgateway.Parameters | — | Push parameters |
Returns Promise<{ resp?: unknown; body?: unknown }> — A promise resolving with the Pushgateway HTTP response and body.
Pushgateway.Parameters
interface Parameters {
/**
* Jobname that is pushing the metric
*/
jobName: string;
/**
* Label sets used in the url when making a request to the Pushgateway,
*/
groupings?: {
[key: string]: string;
};
}Functions
linearBuckets(start: number, width: number, count: number): number[]
Source
Create an array with equal spacing between the elements
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
start | number | — | The first value in the array |
width | number | — | The spacing between the elements |
count | number | — | The number of items in array |
Returns number[] — An array with the requested number of elements
exponentialBuckets(start: number, factor: number, count: number): number[]
Source
Create an array that grows exponentially
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
start | number | — | The first value in the array |
factor | number | — | The exponential factor |
count | number | — | The number of items in array |
Returns number[] — An array with the requested number of elements
validateMetricName(name: string): boolean
Source
Validate a metric name
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The name to validate |
Returns boolean — True if the metric name is valid, false if not
Constants and variables
register: Registry
Source
The register that contains all metrics
contentType: RegistryContentType
Source
HTTP Content-Type for metrics response headers for the default registry, defaults to Prometheus text format.
prometheusContentType: PrometheusContentType
Source
HTTP Prometheus Content-Type for metrics response headers.
openMetricsContentType: OpenMetricsContentType
Source
HTTP OpenMetrics Content-Type for metrics response headers.
MetricType
enum MetricType {
Counter,
Gauge,
Histogram,
Summary,
}collectDefaultMetrics
collectDefaultMetrics: {
/**
* Configure default metrics
* @param config Configuration object for default metrics collector
*/
<T extends RegistryContentType>(
config?: DefaultMetricsCollectorConfiguration<T>,
): void;
/** All available default metrics */
metricsList: string[];
}Types
Charset
type Charset = 'utf-8'PrometheusMIME
type PrometheusMIME = 'text/plain'PrometheusMetricsVersion
type PrometheusMetricsVersion = '0.0.4'OpenMetricsMIME
type OpenMetricsMIME = 'application/openmetrics-text'OpenMetricsVersion
type OpenMetricsVersion = '1.0.0'OpenMetricsContentType
type OpenMetricsContentType = `${OpenMetricsMIME}; version=${OpenMetricsVersion}; charset=${Charset}`PrometheusContentType
type PrometheusContentType = `${PrometheusMIME}; version=${PrometheusMetricsVersion}; charset=${Charset}`RegistryContentType
type RegistryContentType = | PrometheusContentType
| OpenMetricsContentTypeCollector
type Collector = () => voidMetric
type Metric<T extends string = string> = | Counter<T>
| Gauge<T>
| Summary<T>
| Histogram<T>General metric type
Aggregator
type Aggregator = 'omit' | 'sum' | 'first' | 'min' | 'max' | 'average'Aggregation methods, used for aggregating metrics in a Node.js cluster.
CollectFunction
type CollectFunction<T> = (this: T) => void | Promise<void>MetricObject
interface MetricObject {
name: string;
help: string;
type: MetricType;
aggregator: Aggregator;
collect: CollectFunction<any>;
}MetricObjectWithValues
interface MetricObjectWithValues<T extends MetricValue<string>>
extends MetricObject {
values: T[];
}MetricValue
type MetricValue<T extends string> = {
value: number;
labels: LabelValues<T>;
}MetricValueWithName
type MetricValueWithName<T extends string> = MetricValue<T> & {
metricName?: string;
}LabelValues
type LabelValues<T extends string> = Partial<Record<T, string | number>>MetricConfiguration
interface MetricConfiguration<T extends string> {
name: string;
help: string;
labelNames?: T[] | readonly T[];
registers?: (
| Registry<PrometheusContentType>
| Registry<OpenMetricsContentType>
)[];
aggregator?: Aggregator;
collect?: CollectFunction<any>;
enableExemplars?: boolean;
}CounterConfiguration
interface CounterConfiguration<T extends string>
extends MetricConfiguration<T> {
collect?: CollectFunction<Counter<T>>;
}IncreaseDataWithExemplar
interface IncreaseDataWithExemplar<T extends string> {
value?: number;
labels?: LabelValues<T>;
exemplarLabels?: LabelValues<T>;
}ObserveDataWithExemplar
interface ObserveDataWithExemplar<T extends string> {
value: number;
labels?: LabelValues<T>;
exemplarLabels?: LabelValues<T>;
}GaugeConfiguration
interface GaugeConfiguration<T extends string>
extends MetricConfiguration<T> {
collect?: CollectFunction<Gauge<T>>;
}HistogramConfiguration
interface HistogramConfiguration<T extends string>
extends MetricConfiguration<T> {
buckets?: number[];
collect?: CollectFunction<Histogram<T>>;
}SummaryConfiguration
interface SummaryConfiguration<T extends string>
extends MetricConfiguration<T> {
percentiles?: number[];
maxAgeSeconds?: number;
ageBuckets?: number;
pruneAgedBuckets?: boolean;
compressCount?: number;
collect?: CollectFunction<Summary<T>>;
}DefaultMetricsCollectorConfiguration
interface DefaultMetricsCollectorConfiguration<
T extends RegistryContentType,
> {
register?: Registry<T>;
prefix?: string;
gcDurationBuckets?: number[];
eventLoopMonitoringPrecision?: number;
labels?: object;
}See also
- Bare modules — the full
bare-*catalog. - Bare runtime API — the runtime these modules extend.