diff --git a/prometheus_client/metrics.py b/prometheus_client/metrics.py index 34305a17..91cd9ecf 100644 --- a/prometheus_client/metrics.py +++ b/prometheus_client/metrics.py @@ -292,6 +292,12 @@ def f(): # Count only one type of exception with c.count_exceptions(ValueError): pass + + You can also reset the counter to zero in case your logical "process" restarts + without restarting the actual python process. + + c.reset() + """ _type = 'counter' @@ -310,6 +316,11 @@ def inc(self, amount: float = 1, exemplar: Optional[Dict[str, str]] = None) -> N _validate_exemplar(exemplar) self._value.set_exemplar(Exemplar(exemplar, amount, time.time())) + def reset(self) -> None: + """Reset the counter to zero. Use this when a logical process restarts without restarting the actual python process.""" + self._value.set(0) + self._created = time.time() + def count_exceptions(self, exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = Exception) -> ExceptionCounter: """Count exceptions in a block of code or function. diff --git a/tests/test_core.py b/tests/test_core.py index 6f7c9d1c..30f9e0ad 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -43,6 +43,16 @@ def test_increment(self): self.counter.inc(7) self.assertEqual(8, self.registry.get_sample_value('c_total')) + def test_reset(self): + self.counter.inc() + self.assertNotEqual(0, self.registry.get_sample_value('c_total')) + created = self.registry.get_sample_value('c_created') + time.sleep(0.05) + self.counter.reset() + self.assertEqual(0, self.registry.get_sample_value('c_total')) + created_after_reset = self.registry.get_sample_value('c_created') + self.assertLess(created, created_after_reset) + def test_repr(self): self.assertEqual(repr(self.counter), "prometheus_client.metrics.Counter(c)")