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] += valueWhat the code does
Count the functions escape_label_value, exposition and record as the entire surface area of Prometheus Text Exposition.
The file repeats itself only inside for (name, labels), value in sorted(counters.items()).
Applying it
The main signature reads def escape_label_value(value: str) -> str
Callers only need escape_label_value — everything else stays internal.
Statements that matter
def record(counters, name: str, value: float, **labels: str) -> None:
key = (name, tuple(sorted(labels.items())))
counters[key] += value
def escape_label_value(value: str) -> str:
return value.replace('\\', '\\\\').replace('\n', '\\n').replace('"', '\\"')
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `escape_label_value`, `exposition`, `record` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.