Skip to content

Commit

Permalink
Pass metric instance and callback name to Timer
Browse files Browse the repository at this point in the history
This should make the code slightly more readable.

Signed-off-by: Andreas Zeidler <andreas.zeidler@zeit.de>
  • Loading branch information
witsch committed Dec 11, 2021
1 parent 2b57f24 commit 4f400d0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
18 changes: 8 additions & 10 deletions prometheus_client/context_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ def wrapped(func, *args, **kwargs):


class Timer:
def __init__(self, callback):
self._callback = callback
def __init__(self, metric, callback_name):
self._metric = metric
self._callback_name = callback_name

def _new_timer(self):
return self.__class__(self._callback)
return self.__class__(self._metric, self._callback_name)

def __enter__(self):
self._start = default_timer()
Expand All @@ -55,15 +56,12 @@ def __enter__(self):
def __exit__(self, typ, value, traceback):
# Time can go backwards.
duration = max(default_timer() - self._start, 0)
instance = self._callback.__self__
instance._raise_if_not_observable()
self._callback(duration)
self._metric._raise_if_not_observable()
callback = getattr(self._metric, self._callback_name)
callback(duration)

def labels(self, *args, **kw):
instance = self._callback.__self__
self._callback = getattr(
instance.labels(*args, **kw),
self._callback.__name__)
self._metric = self._metric.labels(*args, **kw)

def __call__(self, f):
def wrapped(func, *args, **kwargs):
Expand Down
6 changes: 3 additions & 3 deletions prometheus_client/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ def time(self):
Can be used as a function decorator or context manager.
"""
return Timer(self.set)
return Timer(self, 'set')

def set_function(self, f):
"""Call the provided function to return the Gauge value.
Expand Down Expand Up @@ -474,7 +474,7 @@ def time(self):
Can be used as a function decorator or context manager.
"""
return Timer(self.observe)
return Timer(self, 'observe')

def _child_samples(self):
return (
Expand Down Expand Up @@ -598,7 +598,7 @@ def time(self):
Can be used as a function decorator or context manager.
"""
return Timer(self.observe)
return Timer(self, 'observe')

def _child_samples(self):
samples = []
Expand Down

0 comments on commit 4f400d0

Please sign in to comment.