86 return |
86 return |
87 _bucket, _address = bucket, address |
87 _bucket, _address = bucket, address |
88 _socket = socket.socket(family, socket.SOCK_DGRAM) |
88 _socket = socket.socket(family, socket.SOCK_DGRAM) |
89 |
89 |
90 |
90 |
|
91 def teardown(): |
|
92 """Unconfigure the statsd endpoint |
|
93 |
|
94 This is most likely only useful for unit tests""" |
|
95 global _bucket, _address, _socket |
|
96 _bucket = 'cubicweb' |
|
97 _address = None |
|
98 _socket = None |
|
99 |
|
100 |
91 def statsd_c(context, n=1): |
101 def statsd_c(context, n=1): |
92 if _address is not None: |
102 if _address is not None: |
93 _socket.sendto('{0}.{1}:{2}|c\n'.format(_bucket, context, n), _address) |
103 _socket.sendto('{0}.{1}:{2}|c\n'.format(_bucket, context, n).encode(), |
|
104 _address) |
94 |
105 |
95 |
106 |
96 def statsd_g(context, value): |
107 def statsd_g(context, value): |
97 if _address is not None: |
108 if _address is not None: |
98 _socket.sendto('{0}.{1}:{2}|g\n'.format(_bucket, context, value), _address) |
109 _socket.sendto('{0}.{1}:{2}|g\n'.format(_bucket, context, value).encode(), |
|
110 _address) |
99 |
111 |
100 |
112 |
101 def statsd_t(context, value): |
113 def statsd_t(context, value): |
102 if _address is not None: |
114 if _address is not None: |
103 _socket.sendto('{0}.{1}:{2:.4f}|ms\n'.format(_bucket, context, value), _address) |
115 _socket.sendto('{0}.{1}:{2:.4f}|ms\n'.format(_bucket, context, value).encode(), |
|
116 _address) |
104 |
117 |
105 |
118 |
106 class statsd_timeit(object): |
119 class statsd_timeit(object): |
107 __slots__ = ('callable',) |
120 __slots__ = ('callable',) |
108 |
121 |
124 try: |
137 try: |
125 return self.callable(*args, **kw) |
138 return self.callable(*args, **kw) |
126 finally: |
139 finally: |
127 dt = 1000 * (time.time() - t0) |
140 dt = 1000 * (time.time() - t0) |
128 msg = '{0}.{1}:{2:.4f}|ms\n{0}.{1}:1|c\n'.format( |
141 msg = '{0}.{1}:{2:.4f}|ms\n{0}.{1}:1|c\n'.format( |
129 _bucket, self.__name__, dt) |
142 _bucket, self.__name__, dt).encode() |
130 _socket.sendto(msg, _address) |
143 _socket.sendto(msg, _address) |
131 |
144 |
132 def __get__(self, obj, objtype): |
145 def __get__(self, obj, objtype): |
133 """Support instance methods.""" |
146 """Support instance methods.""" |
134 if obj is None: # class method or some already wrapped method |
147 if obj is None: # class method or some already wrapped method |
145 yield |
158 yield |
146 finally: |
159 finally: |
147 if _address is not None: |
160 if _address is not None: |
148 dt = 1000 * (time.time() - t0) |
161 dt = 1000 * (time.time() - t0) |
149 msg = '{0}.{1}:{2:.4f}|ms\n{0}.{1}:1|c\n'.format( |
162 msg = '{0}.{1}:{2:.4f}|ms\n{0}.{1}:1|c\n'.format( |
150 _bucket, ctxmsg, dt) |
163 _bucket, ctxmsg, dt).encode() |
151 _socket.sendto(msg, _address) |
164 _socket.sendto(msg, _address) |