-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprometheus.py
More file actions
72 lines (56 loc) · 2.35 KB
/
Copy pathprometheus.py
File metadata and controls
72 lines (56 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
import json
import prometheus_client
from prometheus_client import CollectorRegistry
prometheus_client.disable_created_metrics()
prometheus_client.REGISTRY.unregister(prometheus_client.GC_COLLECTOR)
prometheus_client.REGISTRY.unregister(prometheus_client.PLATFORM_COLLECTOR)
prometheus_client.REGISTRY.unregister(prometheus_client.PROCESS_COLLECTOR)
def reset():
for collector in prometheus_client.REGISTRY._collector_to_names:
if "_value" in dir(collector):
# case Counter without labels
collector._value.set(0)
elif "_metrics" in dir(collector):
for metric in collector._metrics.values():
if "_value" in dir(metric):
# case Counter with labels
metric._value.set(0)
elif "_buckets" in dir(metric) and "_sum" in dir(metric):
# case Histogram with labels
metric._sum.set(0)
for bucket in metric._buckets:
bucket.set(0)
elif "_buckets" in dir(collector) and "_sum" in dir(collector):
# case Histogram without labels
collector._sum.set(0)
for bucket in collector._buckets:
bucket.set(0)
def filter_metrics(m):
# Other metric types are not supported so far
if m._type not in ("counter", "histogram"):
return False
# Empty metrics with labels are exported without values
dir_m = dir(m)
if "_value" in dir_m and m._value._value == 0:
return False
if "_buckets" in dir_m and m._sum._value == 0:
return False
if "_metrics" in dir_m:
for metric in m._metrics.values():
if ("_value" in dir(metric) and metric._value._value > 0) or ("_sum" in dir(metric) and metric._sum._value > 0):
return True
return False
return True
def get_metrics():
new_registry = CollectorRegistry(auto_describe=True)
for collector in filter(filter_metrics, prometheus_client.REGISTRY._collector_to_names):
new_registry.register(collector)
return prometheus_client.generate_latest(new_registry).decode("utf-8")
def flush_metrics():
metrics = get_metrics()
if not metrics or len(metrics) == 0:
return
if os.environ.get("PYTEST_CURRENT_TEST"):
return
print("PROMLOG [" + json.dumps(metrics) + "]")