OLD | NEW |
| (Empty) |
1 # Copyright 2015 The Chromium Authors. All rights reserved. | |
2 # Use of this source code is governed by a BSD-style license that can be | |
3 # found in the LICENSE file. | |
4 | |
5 """Helper classes that make it easier to instrument code for monitoring.""" | |
6 | |
7 | |
8 class ScopedIncrementCounter(object): | |
9 """Increment a counter when the wrapped code exits. | |
10 | |
11 The counter will be given a 'status' = 'success' or 'failure' label whose | |
12 value will be set to depending on whether the wrapped code threw an exception. | |
13 | |
14 Example: | |
15 | |
16 mycounter = Counter('foo/stuff_done') | |
17 with ScopedIncrementCounter(mycounter): | |
18 DoStuff() | |
19 | |
20 To set a custom status label and status value: | |
21 | |
22 mycounter = Counter('foo/http_requests') | |
23 with ScopedIncrementCounter(mycounter, 'response_code') as sc: | |
24 status = MakeHttpRequest() | |
25 sc.set_status(status) # This custom status now won't be overwritten if | |
26 # the code later raises an exception. | |
27 """ | |
28 | |
29 def __init__(self, counter, label='status', success_value='success', | |
30 failure_value='failure'): | |
31 self.counter = counter | |
32 self.label = label | |
33 self.success_value = success_value | |
34 self.failure_value = failure_value | |
35 self.status = None | |
36 | |
37 def set_failure(self): | |
38 self.set_status(self.failure_value) | |
39 | |
40 def set_status(self, status): | |
41 self.status = status | |
42 | |
43 def __enter__(self): | |
44 self.status = None | |
45 return self | |
46 | |
47 def __exit__(self, exc_type, exc_value, traceback): | |
48 if self.status is None: | |
49 if exc_type is None: | |
50 self.status = self.success_value | |
51 else: | |
52 self.status = self.failure_value | |
53 self.counter.increment({self.label: self.status}) | |
OLD | NEW |