8000 Reset counter (#1005) · prometheus/client_python@1f8ceb7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1f8ceb7

Browse files
Reset counter (#1005)
* Add .reset method to Counter metric * Update method docstring * Add a test for .reset() method Signed-off-by: Paul Melnikov <positron96@gmail.com> Co-authored-by: Chris Marchbanks <csmarchbanks@gmail.com>
1 parent b9edc43 commit 1f8ceb7

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

prometheus_client/metrics.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,12 @@ def f():
292292
# Count only one type of exception
293293
with c.count_exceptions(ValueError):
294294
pass
295+
296+
You can also reset the counter to zero in case your logical "process" restarts
297+
without restarting the actual python process.
298+
299+
c.reset()
300+
295301 8000
"""
296302
_type = 'counter'
297303

@@ -310,6 +316,11 @@ def inc(self, amount: float = 1, exemplar: Optional[Dict[str, str]] = None) -> N
310316
_validate_exemplar(exemplar)
311317
self._value.set_exemplar(Exemplar(exemplar, amount, time.time()))
312318

319+
def reset(self) -> None:
320+
"""Reset the counter to zero. Use this when a logical process restarts without restarting the actual python process."""
321+
self._value.set(0)
322+
self._created = time.time()
323+
313324
def count_exceptions(self, exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = Exception) -> ExceptionCounter:
314325
"""Count exceptions in a block of code or function.
315326

tests/test_core.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ def test_increment(self):
4343
self.counter.inc(7)
4444
self.assertEqual(8, self.registry.get_sample_value('c_total'))
4545

46+
def test_reset(self):
47+
self.counter.inc()
48+
self.assertNotEqual(0, self.registry.get_sample_value('c_total'))
49+
created = self.registry.get_sample_value('c_created')
50+
time.sleep(0.05)
51+
self.counter.reset()
52+
self.assertEqual(0, self.registry.get_sample_value('c_total'))
53+
created_after_reset = self.registry.get_sample_value('c_created')
54+
self.assertLess(created, created_after_reset)
55+
4656
def test_repr(self):
4757
self.assertEqual(repr(self.counter), "prometheus_client.metrics.Counter(c)")
4858

0 commit comments

Comments
 (0)
0