diff --git a/prometheus_client/metrics.py b/prometheus_client/metrics.py index 95770ebd..079fbf27 100644 --- a/prometheus_client/metrics.py +++ b/prometheus_client/metrics.py @@ -257,6 +257,11 @@ def inc(self, amount=1): raise ValueError('Counters can only be incremented by non-negative amounts.') self._value.inc(amount) + def reset(self): + """Reset counter to zero.""" + if hasattr(self, '_value'): + self._value.set(0) + def count_exceptions(self, exception=Exception): """Count exceptions in a block of code or function. diff --git a/prometheus_client/registry.py b/prometheus_client/registry.py index fff1f98c..8f70a53d 100644 --- a/prometheus_client/registry.py +++ b/prometheus_client/registry.py @@ -149,5 +149,17 @@ def get_sample_value(self, name, labels=None): return s.value return None + def reset_metrics(self): + """Reset all the counter type metrics from all collectors in registry""" + + for metric in self.collect(): + if metric.type == 'counter': + if hasattr(self._names_to_collectors[metric.name], '_metrics'): + for sub_metric in self._names_to_collectors[metric.name]._metrics: + self._names_to_collectors[metric.name]._metrics[sub_metric].reset() + else: + if hasattr(self._names_to_collectors[metric.name], 'reset'): + self._names_to_collectors[metric.name].reset() + REGISTRY = CollectorRegistry(auto_describe=True) diff --git a/tests/test_core.py b/tests/test_core.py index 5a81f122..40347df2 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -30,13 +30,21 @@ def test_increment(self): self.assertEqual(1, self.registry.get_sample_value('c_total')) self.counter.inc(7) self.assertEqual(8, self.registry.get_sample_value('c_total')) - + def test_repr(self): self.assertEqual(repr(self.counter), "prometheus_client.metrics.Counter(c)") def test_negative_increment_raises(self): self.assertRaises(ValueError, self.counter.inc, -1) - + + def test_reset(self): + self.assertEqual(0, self.registry.get_sample_value('c_total')) + self.counter.inc() + self.counter.reset() + self.assertEqual(0, self.registry.get_sample_value('c_total')) + self.counter.inc() + self.registry.reset_metrics() + self.assertEqual(0, self.registry.get_sample_value('c_total')) def test_function_decorator(self): @self.counter.count_exceptions(ValueError) @@ -87,7 +95,7 @@ class TestGauge(unittest.TestCase): def setUp(self): self.registry = CollectorRegistry() self.gauge = Gauge('g', 'help', registry=self.registry) - + def test_repr(self): self.assertEqual(repr(self.gauge), "prometheus_client.metrics.Gauge(g)")