Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/content/instrumenting/gauge.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ def process():

with g.time():
pass

with g.time() as t:
pass
print(t.duration) # observed time in seconds.
```

### `set_function(f)`
Expand Down
4 changes: 4 additions & 0 deletions docs/content/instrumenting/histogram.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ def process():

with h.time():
pass

with h.time() as t:
pass
print(t.duration) # observed time in seconds.
```

## Labels
Expand Down
4 changes: 4 additions & 0 deletions docs/content/instrumenting/summary.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ def process():

with s.time():
pass

with s.time() as t:
pass
print(t.duration) # observed time in seconds.
```

## Labels
Expand Down
5 changes: 3 additions & 2 deletions prometheus_client/context_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ class Timer:
def __init__(self, metric, callback_name):
self._metric = metric
self._callback_name = callback_name
self.duration = None

def _new_timer(self):
return self.__class__(self._metric, self._callback_name)
Expand All @@ -65,9 +66,9 @@ def __enter__(self):

def __exit__(self, typ, value, traceback):
# Time can go backwards.
duration = max(default_timer() - self._start, 0)
self.duration = max(default_timer() - self._start, 0)
callback = getattr(self._metric, self._callback_name)
callback(duration)
callback(self.duration)

def labels(self, *args, **kw):
self._metric = self._metric.labels(*args, **kw)
Expand Down
8 changes: 8 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,14 @@ def test_block_decorator_with_label(self):
metric.labels('foo')
self.assertEqual(1, value('s_with_labels_count', {'label1': 'foo'}))

def test_timer_duration_exposed(self):
with self.summary.time() as t:
time.sleep(0.01)
self.assertIsNotNone(t.duration)
self.assertGreater(t.duration, 0)
recorded_sum = self.registry.get_sample_value('s_sum')
self.assertEqual(t.duration, recorded_sum)

def test_timer_not_observable(self):
s = Summary('test', 'help', labelnames=('label',), registry=self.registry)

Expand Down