Prometheus Text Exposition
Expose counters and histograms in the Prometheus text exposition format with metric metadata and correct escaping.
Code
from collections import defaultdict
from typing import Iterable
def escape_label_value(value: str) -> str:
return value.replace('\\', '\\\\').replace('\n', '\\n').replace('"', '\\"')
def exposition(counters: dict[tuple[str, tuple[tuple[str, str], ...]], float]) -> str:
lines: list[str] = []
seen = set()
for (name, labels), value in sorted(counters.items()):
if name not in seen:
lines.append(f'# HELP {name} Application counter.')
lines.append(f'# TYPE {name} counter')
seen.add(name)
rendered = ','.join(f'{k}="{escape_label_value(v)}"' for k, v in labels)
lines.append(f'{name}{{{rendered}}} {value}')
return '\n'.join(lines) + '\n'
def record(counters, name: str, value: float, **labels: str) -> None:
key = (name, tuple(sorted(labels.items())))
counters[key] += valueReport a problem with this exampleOpens a pre-filled issue on GitHub.