Skip to content

Commit

Permalink
Reset counter (#1005)
Browse files Browse the repository at this point in the history
* Add .reset method to Counter metric
* Update method docstring
* Add a test for .reset() method

Signed-off-by: Paul Melnikov <[email protected]>
Co-authored-by: Chris Marchbanks <[email protected]>
  • Loading branch information
positron96 and csmarchbanks authored Feb 13, 2024
1 parent b9edc43 commit 1f8ceb7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
11 changes: 11 additions & 0 deletions prometheus_client/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)")

Expand Down

0 comments on commit 1f8ceb7

Please sign in to comment.