22
33import copy
44import re
5+ import time
6+ from contextlib import contextmanager
57from BaseHTTPServer import BaseHTTPRequestHandler
8+ from functools import wraps
69from threading import Lock
710
811__all__ = ['Counter' , 'Gauge' , 'Summary' ]
@@ -165,6 +168,23 @@ def inc(self, amount=1):
165168 with self ._lock :
166169 self ._value += amount
167170
171+ @contextmanager
172+ def trackBlockRaises (self ):
173+ """Decorator to increment if a block raises an exception."""
174+ try :
175+ yield
176+ except Exception , e :
177+ self .inc ()
178+ raise e
179+
180+ def trackFunctionRaises (self , f ):
181+ """Decorator to increment if a function raises an exception."""
182+ @wraps (f )
183+ def wrapper (* args , ** kwargs ):
184+ with self .trackBlockRaises ():
185+ return f (* args , ** kwargs )
186+ return wrapper
187+
168188 def _samples (self ):
169189 with self ._lock :
170190 return (('' , {}, self ._value ), )
@@ -187,10 +207,31 @@ def dec(self, amount=1):
187207 self ._value -= amount
188208
189209 def set (self , value ):
190- """Set gauge to the given amount ."""
210+ """Set gauge to the given value ."""
191211 with self ._lock :
192212 self ._value = float (value )
193213
214+ def setToCurrentTime (self , value ):
215+ """Set gauge to the current unixtime."""
216+ self .set (time .time ())
217+
218+ @contextmanager
219+ def trackBlockInprogress (self ):
220+ """Decorator to track how many of a block are in progress."""
221+ self .inc ()
222+ try :
223+ yield
224+ finally :
225+ self .dec ()
226+
227+ def trackFunctionInprogress (self , f ):
228+ """Decorator to track how many of a function are in progress."""
229+ @wraps (f )
230+ def wrapper (* args , ** kwargs ):
231+ with self .trackBlockInprogress ():
232+ return f (* args , ** kwargs )
233+ return wrapper
234+
194235 def _samples (self ):
195236 with self ._lock :
196237 return (('' , {}, self ._value ), )
@@ -209,6 +250,24 @@ def observe(self, amount):
209250 self ._count += 1
210251 self ._sum += amount
211252
253+ @contextmanager
254+ def timeBlock (self ):
255+ """Context manager to time how long a block of code takes in seconds."""
256+ start = time .time ()
257+ try :
258+ yield
259+ finally :
260+ # Time can go backwards.
261+ self .observe (max (time .time () - start , 0 ))
262+
263+ def timeFunction (self , f ):
264+ """Decorator to time long a function takes in seconds."""
265+ @wraps (f )
266+ def wrapper (* args , ** kwargs ):
267+ with self .timeBlock ():
268+ return f (* args , ** kwargs )
269+ return wrapper
270+
212271 def _samples (self ):
213272 with self ._lock :
214273 return (
@@ -257,7 +316,6 @@ def do_GET(self):
257316 s = Summary ('ss' , 'A summary' , ['a' , 'b' ])
258317 s .labels ('c' , 'd' ).observe (17 )
259318
260-
261319 from BaseHTTPServer import HTTPServer
262320 server_address = ('' , 8000 )
263321 httpd = HTTPServer (server_address , MetricsHandler )
0 commit comments