diff --git a/packages/lib/prometheus.js b/packages/lib/prometheus.js index aaf34c11..bb163ea2 100644 --- a/packages/lib/prometheus.js +++ b/packages/lib/prometheus.js @@ -723,6 +723,21 @@ class GaugeChild extends ValueCollectorChild { setToCurrentTime() { this._values.set(this._key, Date.now() / 1000); } + + /** + * Start a timer for setting a duration for label set + * + * @returns {function()} + * function that when called will set the guage to the duration in + * seconds from when the timer was started + */ + startTimer() { + let start = process.hrtime.bigint(); + return () => { + let end = process.hrtime.bigint(); + this.set(Number(end - start) / 1e9); + }; + } } /** @@ -886,6 +901,18 @@ class Gauge extends ValueCollector { setToCurrentTime() { this._defaultChild.setToCurrentTime(); } + + /** + * Start a timer for setting a duration + * + * Note: Only works if this is an unlabeled collector. + * @returns {function()} + * function that when called will set the guage to the duration in + * seconds from when the timer was started + */ + startTimer() { + return this._defaultChild.startTimer(); + } } function formatValue(value) { diff --git a/test/lib/prometheus.js b/test/lib/prometheus.js index 6507c197..12d75532 100644 --- a/test/lib/prometheus.js +++ b/test/lib/prometheus.js @@ -198,6 +198,16 @@ describe("lib/prometheus", function() { ); }); }); + describe(".startTimer()", function() { + it("should set the gauge to a short duration", function() { + let setDuration = gauge.startTimer(); + setDuration(); + assert( + gauge._values.get("") > 0 && gauge._values.get("") < 1, + "value set is not between 0 and 1" + ); + }); + }); }); describe("class Histogram", function() {