def test_summary(self): """Test that we can track summaries in Service303""" # Add a summary with a label to the regisry c = Summary('process_max_fds', 'A summary', ['result'], registry=self.registry) c.labels('success').observe(1.23) c.labels('failure').observe(2.34) # Build proto outputs summary1 = metrics_pb2.Summary(sample_count=1, sample_sum=1.23) summary2 = metrics_pb2.Summary(sample_count=1, sample_sum=2.34) metric1 = metrics_pb2.Metric(summary=summary1, timestamp_ms=1234000) metric2 = metrics_pb2.Metric(summary=summary2, timestamp_ms=1234000) family = metrics_pb2.MetricFamily( name=str(metricsd_pb2.process_max_fds), type=metrics_pb2.SUMMARY) metric1.label.add( name=str(metricsd_pb2.result), value='success') metric2.label.add( name=str(metricsd_pb2.result), value='failure') family.metric.extend([metric1, metric2]) with unittest.mock.patch('time.time') as mock_time: mock_time.side_effect = lambda: 1234 self.assertCountEqual(list(metrics_export.get_metrics(self.registry))[0].metric, family.metric)
def _summary_to_proto( metric: prometheus_client.core.Metric, ) -> [metrics_pb2.MetricFamily]: """ 1. Get metrics by unique labelset ignoring quantile 2. convert to proto separately for each one """ family_by_labelset = {} for sample in metric.samples: (name, labels, value, *_) = sample # get real family by checking labels (ignoring quantile) distinct_labels = frozenset(_remove_label(labels, 'quantile').items()) if distinct_labels not in family_by_labelset: fam = metrics_pb2.MetricFamily( name=metric.name, type=metrics_pb2.SUMMARY, ) summ = metrics_pb2.Summary(sample_count=0, sample_sum=0) fam.metric.extend([metrics_pb2.Metric(summary=summ)]) family_by_labelset[distinct_labels] = fam unique_family = family_by_labelset[distinct_labels] if str.endswith(name, "_sum"): unique_family.metric[0].summary.sample_sum = value elif str.endswith(name, "_count"): unique_family.metric[0].summary.sample_count = int(value) elif 'quantile' in labels: unique_family.metric[0].summary.quantile.extend([ metrics_pb2.Quantile( quantile=float(labels['quantile']), value=value, ), ]) # Add non-quantile labels to all metrics for labelset in family_by_labelset.keys(): for label in labelset: family_by_labelset[labelset].metric[0].label.add( name=label[0], value=label[1], ) return list(family_by_labelset.values())