-
Notifications
You must be signed in to change notification settings - Fork 853
Expand file tree
/
Copy pathexposition.py
More file actions
72 lines (64 loc) · 3.02 KB
/
exposition.py
File metadata and controls
72 lines (64 loc) · 3.02 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
#!/usr/bin/python
from __future__ import unicode_literals
from ..utils import floatToGoString
CONTENT_TYPE_LATEST = str('application/openmetrics-text; version=0.0.1; charset=utf-8')
"""Content type of the latest OpenMetrics text format"""
def _to_openmetrics_value(value):
# Openmetrics distinguishes integers and floats with different text representations.
if type(value) == int:
return str(value)
return floatToGoString(value)
def generate_latest(registry):
'''Returns the metrics from the registry in latest text format as a string.'''
output = []
for metric in registry.collect():
try:
mname = metric.name
output.append('# HELP {0} {1}\n'.format(
mname, metric.documentation.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"')))
output.append('# TYPE {0} {1}\n'.format(mname, metric.type))
if metric.unit:
output.append('# UNIT {0} {1}\n'.format(mname, metric.unit))
for s in metric.samples:
if s.labels:
labelstr = '{{{0}}}'.format(','.join(
['{0}="{1}"'.format(
k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
for k, v in sorted(s.labels.items())]))
else:
labelstr = ''
if s.exemplar:
if metric.type not in ('histogram', 'gaugehistogram') or not s.name.endswith('_bucket'):
raise ValueError("Metric {0} has exemplars, but is not a histogram bucket".format(metric.name))
labels = '{{{0}}}'.format(','.join(
['{0}="{1}"'.format(
k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
for k, v in sorted(s.exemplar.labels.items())]))
if s.exemplar.timestamp is not None:
exemplarstr = ' # {0} {1} {2}'.format(
labels,
_to_openmetrics_value(s.exemplar.value),
s.exemplar.timestamp,
)
else:
exemplarstr = ' # {0} {1}'.format(
labels,
_to_openmetrics_value(s.exemplar.value),
)
else:
exemplarstr = ''
timestamp = ''
if s.timestamp is not None:
timestamp = ' {0}'.format(s.timestamp)
output.append('{0}{1} {2}{3}{4}\n'.format(
s.name,
labelstr,
_to_openmetrics_value(s.value),
timestamp,
exemplarstr,
))
except Exception as exception:
exception.args = (exception.args or ('',)) + (metric,)
raise
output.append('# EOF\n')
return ''.join(output).encode('utf-8')