Commit beefde7b authored by David Douard's avatar David Douard
Browse files

[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():
    with statsd_timethis('some context message'):
parent 73634b5447e2
......@@ -58,6 +58,7 @@ or a method and the number of calls. It will send a message like::
import time
import socket
from contextlib import contextmanager
_bucket = 'cubicweb'
_address = None
......@@ -134,3 +135,17 @@ class statsd_timeit(object):
return self
import functools
return functools.partial(self.__call__, obj)
def statsd_timethis(ctxmsg):
if _address is not None:
t0 = time.time()
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)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment