Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow adding arbitrary labels to metrics when generating output #740

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,15 +135,16 @@ def start_wsgi_server(port, addr='', registry=REGISTRY):
start_http_server = start_wsgi_server


def generate_latest(registry=REGISTRY):
def generate_latest(registry=REGISTRY, extra_labels={}):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is to be accepted we would also want this in openmetrics/exposition.py.

"""Returns the metrics from the registry in latest text format as a string."""

def sample_line(line):
if line.labels:
labels = {**line.labels, **extra_labels}
if labels:
labelstr = '{{{0}}}'.format(','.join(
['{}="{}"'.format(
k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
for k, v in sorted(line.labels.items())]))
for k, v in sorted(labels.items())]))
else:
labelstr = ''
timestamp = ''
Expand Down
20 changes: 20 additions & 0 deletions tests/test_exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,26 @@ def collect(self):
ts{foo="f"} 0.0 123000
""", generate_latest(self.registry))

def test_extra_labels(self):
c1 = Counter('c1', 'A counter', ["label1"], registry=self.registry)
c1.labels(label1="value1").inc()
c2 = Counter('c2', 'Another counter', registry=self.registry)
c2.inc()
extra_labels = {"label2": "value2"}
self.assertEqual(b"""# HELP c1_total A counter
# TYPE c1_total counter
c1_total{label1="value1",label2="value2"} 1.0
# HELP c1_created A counter
# TYPE c1_created gauge
c1_created{label1="value1",label2="value2"} 123.456
# HELP c2_total Another counter
# TYPE c2_total counter
c2_total{label2="value2"} 1.0
# HELP c2_created Another counter
# TYPE c2_created gauge
c2_created{label2="value2"} 123.456
""", generate_latest(self.registry, extra_labels))


class TestPushGateway(unittest.TestCase):
def setUp(self):
Expand Down