statsd: added option to use timer without auto-sending data

This commit is contained in:
RhodeCode Admin 2022-10-27 15:31:50 +02:00
parent 877b1f16b8
commit cff104fdd7
2 changed files with 13 additions and 2 deletions

View file

@ -45,6 +45,15 @@ class StatsClientBase(object):
raise NotImplementedError()
def timer(self, stat, rate=1, tags=None):
"""
statsd = StatsdClient()
with statsd.timer('bucket_name', auto_send=True) as tmr:
# This block will be timed.
for i in xrange(0, 100000):
i ** 2
# you can access time here...
elapsed_ms = tmr.ms
"""
return Timer(self, stat, rate, tags)
def timing(self, stat, delta, rate=1, tags=None, use_decimals=True):

View file

@ -21,7 +21,7 @@ def safe_wraps(wrapper, *args, **kwargs):
class Timer(object):
"""A context manager/decorator for statsd.timing()."""
def __init__(self, client, stat, rate=1, tags=None, use_decimals=True):
def __init__(self, client, stat, rate=1, tags=None, use_decimals=True, auto_send=True):
self.client = client
self.stat = stat
self.rate = rate
@ -30,6 +30,7 @@ class Timer(object):
self._sent = False
self._start_time = None
self.use_decimals = use_decimals
self.auto_send = auto_send
def __call__(self, f):
"""Thread-safe timing function decorator."""
@ -41,13 +42,14 @@ class Timer(object):
finally:
elapsed_time_ms = 1000.0 * (time_now() - start_time)
self.client.timing(self.stat, elapsed_time_ms, self.rate, self.tags, self.use_decimals)
self._sent = True
return _wrapped
def __enter__(self):
return self.start()
def __exit__(self, typ, value, tb):
self.stop()
self.stop(send=self.auto_send)
def start(self):
self.ms = None