[statsd] add a statsd_timethis context manager
This context manager allows to report to statsd the execution time of any
piece of code, without the need for it to be a function or a method, like::
def some_function():
do_stuff()
with statsd_timethis('some context message'):
do_that()
ensure_this()
--- a/cubicweb/statsd_logger.py Tue Apr 24 14:16:14 2018 +0200
+++ b/cubicweb/statsd_logger.py Mon Nov 13 16:08:58 2017 +0100
@@ -58,6 +58,7 @@
import time
import socket
+from contextlib import contextmanager
_bucket = 'cubicweb'
_address = None
@@ -134,3 +135,17 @@
return self
import functools
return functools.partial(self.__call__, obj)
+
+
+@contextmanager
+def statsd_timethis(ctxmsg):
+ if _address is not None:
+ t0 = time.time()
+ try:
+ yield
+ finally:
+ if _address is not None:
+ dt = 1000 * (time.time() - t0)
+ msg = '{0}.{1}:{2:.4f}|ms\n{0}.{1}:1|c\n'.format(
+ _bucket, ctxmsg, dt)
+ _socket.sendto(msg, _address)