# HG changeset patch # User David Douard # Date 1510585738 -3600 # Node ID 0d474f888f4a1e2f4fec060113c8ab1286a26dab # Parent 73634b5447e2532014f181f92a80d87c4918c3d2 [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() diff -r 73634b5447e2 -r 0d474f888f4a cubicweb/statsd_logger.py --- 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)