Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add defaultLabels option to metric classes #600

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"es6": true
},
"parserOptions": {
"ecmaVersion": 2019
"ecmaVersion": 2020
},
"rules": {
"no-underscore-dangle": "off",
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ project adheres to [Semantic Versioning](http://semver.org/).

- Allow Pushgateway to now require job names for compatibility with Gravel Gateway.
- Allow `histogram.startTime()` to be used with exemplars.
- added `defaultLabels` option to metric classes

## [15.0.0] - 2023-10-09

Expand Down
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,55 @@ Default labels will be overridden if there is a name conflict.

`register.clear()` will clear default labels.

##### Per-metric default label values

Static labels values may also be applied per-metric:

```js
const counter = new client.Counter({
name: 'metric_name',
help: 'metric_help',
labels: ['method', 'endpoint', 'protocol'],
defaultLabels: {
protocol: 'https',
},
});

// will be recorded with method: "GET", endpoint: "/test", protocol: "https"
counter.labels({ method: 'GET', endpoint: '/test' }).inc();
counter.inc({ method: 'GET', endpoint: '/test' });
```

Default values can also be overridden when recording a value:

```js
// the following are all equivalent:
counter.labels('GET', '/test', 'http').inc();

counter
.labels({
method: 'GET',
endpoint: '/test',
protocol: 'http',
})
.inc();

counter.inc({
method: 'GET',
endpoint: '/test',
protocol: 'http',
});
```

Note that the following shorthand _can't_ be used, unless all labels are specified, including labels with a default value:

```js
// this is good
counter.labels('GET', '/test', 'https').inc();
// this will throw an error
counter.labels('GET', '/test').inc();
```

### Exemplars

The exemplars defined in the OpenMetrics specification can be enabled on Counter
Expand Down
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ interface MetricConfiguration<T extends string> {
| Registry<PrometheusContentType>
| Registry<OpenMetricsContentType>
)[];
defaultLabels: Partial<Record<T, string | number>>;
aggregator?: Aggregator;
collect?: CollectFunction<any>;
enableExemplars?: boolean;
Expand Down
12 changes: 7 additions & 5 deletions lib/counter.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ class Counter extends Metric {
constructor(config) {
super(config);
this.type = 'counter';
this.defaultLabels = {};
this.defaultValue = 1;
this.defaultExemplarLabelSet = {};
if (config.enableExemplars) {
Expand All @@ -40,11 +39,12 @@ class Counter extends Metric {
incWithoutExemplar(labels, value) {
let hash = '';
if (isObject(labels)) {
labels = { ...this.defaultLabels, ...labels };
hash = hashObject(labels, this.sortedLabelNames);
validateLabel(this.labelNames, labels);
} else {
value = labels;
labels = {};
labels = this.defaultLabels;
}

if (value && !Number.isFinite(value)) {
Expand Down Expand Up @@ -76,10 +76,11 @@ class Counter extends Metric {
* @returns {void}
*/
incWithExemplar({
labels = this.defaultLabels,
labels,
value = this.defaultValue,
exemplarLabels = this.defaultExemplarLabelSet,
} = {}) {
labels = { ...this.defaultLabels, ...labels };
const res = this.incWithoutExemplar(labels, value);
this.updateExemplar(exemplarLabels, value, res.labelHash);
}
Expand Down Expand Up @@ -128,8 +129,9 @@ class Counter extends Metric {
}

remove(...args) {
const labels = getLabels(this.labelNames, args) || {};
validateLabel(this.labelNames, labels);
const labelsFromArgs = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labelsFromArgs);
const labels = { ...this.defaultLabels, ...labelsFromArgs };
return removeLabels.call(this, this.hashMap, labels, this.sortedLabelNames);
}
}
Expand Down
12 changes: 7 additions & 5 deletions lib/gauge.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class Gauge extends Metric {
*/
set(labels, value) {
value = getValueArg(labels, value);
labels = getLabelArg(labels);
labels = { ...this.defaultLabels, ...getLabelArg(labels) };
set(this, labels, value);
}

Expand All @@ -53,7 +53,7 @@ class Gauge extends Metric {
*/
inc(labels, value) {
value = getValueArg(labels, value);
labels = getLabelArg(labels);
labels = { ...this.defaultLabels, ...getLabelArg(labels) };
if (value === undefined) value = 1;
setDelta(this, labels, value);
}
Expand All @@ -66,7 +66,7 @@ class Gauge extends Metric {
*/
dec(labels, value) {
value = getValueArg(labels, value);
labels = getLabelArg(labels);
labels = { ...this.defaultLabels, ...getLabelArg(labels) };
if (value === undefined) value = 1;
setDelta(this, labels, -value);
}
Expand Down Expand Up @@ -120,6 +120,7 @@ class Gauge extends Metric {
}

_getValue(labels) {
labels = { ...this.defaultLabels, ...labels };
const hash = hashObject(labels || {}, this.sortedLabelNames);
return this.hashMap[hash] ? this.hashMap[hash].value : 0;
}
Expand All @@ -137,8 +138,9 @@ class Gauge extends Metric {
}

remove(...args) {
const labels = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labels);
const labelsFromArgs = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labelsFromArgs);
const labels = { ...this.defaultLabels, ...labelsFromArgs };
removeLabels.call(this, this.hashMap, labels, this.sortedLabelNames);
}
}
Expand Down
34 changes: 26 additions & 8 deletions lib/histogram.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ class Histogram extends Metric {
});

this.type = 'histogram';
this.defaultLabels = {};
this.defaultExemplarLabelSet = {};
this.enableExemplars = false;

Expand Down Expand Up @@ -72,19 +71,28 @@ class Histogram extends Metric {
* @returns {void}
*/
observeWithoutExemplar(labels, value) {
observe.call(this, labels === 0 ? 0 : labels || {})(value);
labels = isObject(labels)
? { ...this.defaultLabels, ...labels }
: labels ?? this.defaultLabels;
observe.call(this, labels)(value);
}

observeWithExemplar({
labels = this.defaultLabels,
labels,
value,
exemplarLabels = this.defaultExemplarLabelSet,
} = {}) {
observe.call(this, labels === 0 ? 0 : labels || {})(value);
labels = isObject(labels)
? { ...this.defaultLabels, ...labels }
: labels ?? this.defaultLabels;
observe.call(this, labels)(value);
this.updateExemplar(labels, value, exemplarLabels);
}

updateExemplar(labels, value, exemplarLabels) {
labels = isObject(labels)
? { ...this.defaultLabels, ...labels }
: labels ?? this.defaultLabels;
const hash = hashObject(labels, this.sortedLabelNames);
const bound = findBound(this.upperBounds, value);
const { bucketExemplars } = this.hashMap[hash];
Expand Down Expand Up @@ -134,6 +142,9 @@ class Histogram extends Metric {
* @returns {void}
*/
zero(labels) {
labels = isObject(labels)
? { ...this.defaultLabels, ...labels }
: labels ?? this.defaultLabels;
const hash = hashObject(labels, this.sortedLabelNames);
this.hashMap[hash] = createBaseValues(
labels,
Expand All @@ -155,23 +166,30 @@ class Histogram extends Metric {
* });
*/
startTimer(labels, exemplarLabels) {
labels = isObject(labels)
? { ...this.defaultLabels, ...labels }
: labels ?? this.defaultLabels;
return this.enableExemplars
? startTimerWithExemplar.call(this, labels, exemplarLabels)()
: startTimer.call(this, labels)();
}

labels(...args) {
const labels = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labels);
const labelsFromArgs = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labelsFromArgs);
const labels = isObject(labelsFromArgs)
? { ...this.defaultLabels, ...labelsFromArgs }
: labelsFromArgs ?? this.defaultLabels;
return {
observe: observe.call(this, labels),
startTimer: startTimer.call(this, labels),
};
}

remove(...args) {
const labels = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labels);
const labelsFromArgs = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labelsFromArgs);
const labels = { ...this.defaultLabels, ...labelsFromArgs };
removeLabels.call(this, this.hashMap, labels, this.sortedLabelNames);
}
}
Expand Down
14 changes: 13 additions & 1 deletion lib/metric.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

const Registry = require('./registry');
const { isObject } = require('./util');
const { validateMetricName, validateLabelName } = require('./validation');
const {
validateMetricName,
validateLabelName,
validateLabel,
} = require('./validation');

/**
* @abstract
Expand All @@ -19,6 +23,7 @@ class Metric {
registers: [Registry.globalRegistry],
aggregator: 'sum',
enableExemplars: false,
defaultLabels: {},
},
defaults,
config,
Expand All @@ -39,6 +44,13 @@ class Metric {
if (!validateLabelName(this.labelNames)) {
throw new Error('Invalid label name');
}
try {
validateLabel(this.labelNames, this.defaultLabels);
} catch (cause) {
const error = new Error('Invalid default label values');
error.cause = cause;
throw error;
}

if (this.collect && typeof this.collect !== 'function') {
throw new Error('Optional "collect" parameter must be a function');
Expand Down
22 changes: 16 additions & 6 deletions lib/summary.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
'use strict';

const util = require('util');
const { getLabels, hashObject, removeLabels } = require('./util');
const { getLabels, hashObject, removeLabels, isObject } = require('./util');
const { validateLabel } = require('./validation');
const { Metric } = require('./metric');
const timeWindowQuantiles = require('./timeWindowQuantiles');
Expand Down Expand Up @@ -45,7 +45,10 @@ class Summary extends Metric {
* @returns {void}
*/
observe(labels, value) {
observe.call(this, labels === 0 ? 0 : labels || {})(value);
labels = isObject(labels)
? { ...this.defaultLabels, ...labels }
: labels ?? this.defaultLabels;
observe.call(this, labels)(value);
}

async get() {
Expand Down Expand Up @@ -100,21 +103,28 @@ class Summary extends Metric {
* });
*/
startTimer(labels) {
labels = isObject(labels)
? { ...this.defaultLabels, ...labels }
: labels ?? this.defaultLabels;
return startTimer.call(this, labels)();
}

labels(...args) {
const labels = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labels);
const labelsFromArgs = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labelsFromArgs);
const labels = isObject(labelsFromArgs)
? { ...this.defaultLabels, ...labelsFromArgs }
: labelsFromArgs ?? this.defaultLabels;
return {
observe: observe.call(this, labels),
startTimer: startTimer.call(this, labels),
};
}

remove(...args) {
const labels = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labels);
const labelsFromArgs = getLabels(this.labelNames, args);
validateLabel(this.labelNames, labelsFromArgs);
const labels = { ...this.defaultLabels, ...labelsFromArgs };
removeLabels.call(this, this.hashMap, labels, this.sortedLabelNames);
}
}
Expand Down
Loading
Loading