|
| 1 | +import logging |
1 | 2 | from collections import Counter
|
2 | 3 | from enum import Enum
|
3 | 4 | from threading import RLock
|
|
9 | 10 | )
|
10 | 11 | from sentry_dynamic_sampling_lib.utils import synchronized
|
11 | 12 |
|
| 13 | +LOGGER = logging.getLogger("SentryWrapper") |
| 14 | + |
12 | 15 |
|
13 | 16 | class Config:
|
14 | 17 | def __init__(self) -> None:
|
@@ -62,33 +65,47 @@ class MetricType(Enum):
|
62 | 65 | class Metric:
|
63 | 66 | def __init__(self) -> None:
|
64 | 67 | self._lock = RLock()
|
65 |
| - self._activate = { |
66 |
| - MetricType.WSGI: False, |
67 |
| - MetricType.CELERY: False, |
68 |
| - } |
69 |
| - self._counters = { |
70 |
| - MetricType.WSGI: Counter(), |
71 |
| - MetricType.CELERY: Counter(), |
| 68 | + self._metrics = { |
| 69 | + MetricType.WSGI: {"activated": False, "data": Counter()}, |
| 70 | + MetricType.CELERY: {"activated": False, "data": Counter()}, |
72 | 71 | }
|
73 | 72 |
|
74 | 73 | def set_mode(self, _type, mode):
|
75 |
| - self._activate[_type] = mode |
| 74 | + self._metrics[_type]["activated"] = mode |
76 | 75 |
|
77 | 76 | def get_mode(self, _type):
|
78 |
| - return self._activate[_type] |
| 77 | + return self._metrics[_type]["activated"] |
79 | 78 |
|
80 | 79 | @synchronized
|
81 | 80 | def count_path(self, path):
|
82 |
| - if self._activate[MetricType.WSGI]: |
83 |
| - self._counters[MetricType.WSGI][path] += 1 |
| 81 | + metric = self._metrics[MetricType.WSGI] |
| 82 | + if metric["activated"]: |
| 83 | + metric["data"][path] += 1 |
84 | 84 |
|
85 | 85 | @synchronized
|
86 | 86 | def count_task(self, path):
|
87 |
| - if self._activate[MetricType.CELERY]: |
88 |
| - self._counters[MetricType.CELERY][path] += 1 |
89 |
| - |
90 |
| - @synchronized |
91 |
| - def get_and_reset(self, _type): |
92 |
| - counter = self._counters[_type] |
93 |
| - self._counters[_type] = Counter() |
94 |
| - return counter |
| 87 | + metric = self._metrics[MetricType.CELERY] |
| 88 | + if metric["activated"]: |
| 89 | + metric["data"][path] += 1 |
| 90 | + |
| 91 | + def __iter__(self): |
| 92 | + """ |
| 93 | + List activated non-empty metrics |
| 94 | +
|
| 95 | + Yields: |
| 96 | + Tuple(MetricType, Counter): the activated non-empty metrics |
| 97 | + """ |
| 98 | + for metric_type, metric in self._metrics.items(): |
| 99 | + # check if metric is activated |
| 100 | + if not metric["activated"]: |
| 101 | + LOGGER.debug("Metric %s disabled", metric_type.value) |
| 102 | + with self._lock: |
| 103 | + # check im metric is empty |
| 104 | + if len(metric["data"]) == 0: |
| 105 | + LOGGER.debug("Metric %s is empty", metric_type.value) |
| 106 | + continue |
| 107 | + data = metric["data"] |
| 108 | + metric["data"] = Counter() |
| 109 | + |
| 110 | + # yield outside of the lock to not block write while callee execute |
| 111 | + yield metric_type, data |
0 commit comments