Timer and counter context manager for easily sending counter statistics with builtin timer.
| 169 | |
| 170 | |
| 171 | class CounterWithTimer(object): |
| 172 | """ |
| 173 | Timer and counter context manager for easily sending counter statistics |
| 174 | with builtin timer. |
| 175 | """ |
| 176 | |
| 177 | def __init__(self, key, include_parameter=False): |
| 178 | check_key(key) |
| 179 | self.key = key |
| 180 | self._metrics = get_driver() |
| 181 | self._include_parameter = include_parameter |
| 182 | self._start_time = None |
| 183 | |
| 184 | def send_time(self, key=None): |
| 185 | """ |
| 186 | Send current time from start time. |
| 187 | """ |
| 188 | time_delta = self.get_time_delta() |
| 189 | |
| 190 | if key: |
| 191 | check_key(key) |
| 192 | self._metrics.time(key, time_delta.total_seconds()) |
| 193 | else: |
| 194 | self._metrics.time(self.key, time_delta.total_seconds()) |
| 195 | |
| 196 | def get_time_delta(self): |
| 197 | """ |
| 198 | Get current time delta. |
| 199 | """ |
| 200 | return get_datetime_utc_now() - self._start_time |
| 201 | |
| 202 | def __enter__(self): |
| 203 | self._metrics.inc_counter(self.key) |
| 204 | self._start_time = get_datetime_utc_now() |
| 205 | return self |
| 206 | |
| 207 | def __exit__(self, *args): |
| 208 | self.send_time() |
| 209 | |
| 210 | def __call__(self, func): |
| 211 | @wraps(func) |
| 212 | def wrapper(*args, **kw): |
| 213 | with self as counter_with_timer: |
| 214 | if self._include_parameter: |
| 215 | kw["metrics_counter_with_timer"] = counter_with_timer |
| 216 | return func(*args, **kw) |
| 217 | |
| 218 | return wrapper |
| 219 | |
| 220 | |
| 221 | def metrics_initialize(): |
no outgoing calls
no test coverage detected