def _format_line(self, name, labels, value, const_labels=None): labels_str = "" ts = "" # Unify the const_labels and labels # Consta labels have lower priority than labels labels = utils.unify_labels(labels, const_labels, True) # Create the label string if labels: labels_str = [ TextFormat.LABEL_FMT.format(key=k, value=v) for k, v in labels.items() ] labels_str = TextFormat.LABEL_SEPARATOR_FMT.join(labels_str) labels_str = "{{{labels}}}".format(labels=labels_str) if self.timestamp: ts = utils.get_timestamp() result = TextFormat.COUNTER_FMT.format(name=name, labels=labels_str, value=value, timestamp=ts) return result.strip()
def test_union(self): const_labels = {'a': 'b', 'c': 'd'} labels = {'e': 'f', 'g': 'h'} result = utils.unify_labels(labels, const_labels) valid_result = {'g': 'h', 'c': 'd', 'e': 'f', 'a': 'b'} self.assertEqual(valid_result, result)
def _format_gauge(self, gauge, name, const_labels): labels = utils.unify_labels(gauge[0], const_labels, ordered=True) pb2_labels = self._create_pb2_labels(labels) gauge = metrics_pb2.Gauge(value=gauge[1]) metric = metrics_pb2.Metric(label=pb2_labels, gauge=gauge) if self.timestamp: metric.timestamp_ms = utils.get_timestamp() return metric
def test_union_order(self): const_labels = {'a': 'b', 'c': 'd'} labels = {'e': 'f', 'g': 'h'} result = utils.unify_labels(labels, const_labels, True) valid_result = OrderedDict([('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]) self.assertEqual(valid_result, result)
def _format_counter(self, counter, name, const_labels): labels = utils.unify_labels(counter[0], const_labels, ordered=True) # With a counter and labelpairs we do a Metric pb2_labels = self._create_pb2_labels(labels) counter = metrics_pb2.Counter(value=counter[1]) metric = metrics_pb2.Metric(label=pb2_labels, counter=counter) if self.timestamp: metric.timestamp_ms = utils.get_timestamp() return metric
def _format_summary(self, summary, name, const_labels): labels = utils.unify_labels(summary[0], const_labels, ordered=True) pb2_labels = self._create_pb2_labels(labels) # Create the quantiles quantiles = [] for k, v in summary[1].items(): if not isinstance(k, str): q = metrics_pb2.Quantile(quantile=k, value=v) quantiles.append(q) summary = metrics_pb2.Summary(sample_count=summary[1]['count'], sample_sum=summary[1]['sum'], quantile=quantiles) metric = metrics_pb2.Metric(label=pb2_labels, summary=summary) if self.timestamp: metric.timestamp_ms = utils.get_timestamp() return metric
def test_no_const_labels(self): labels = {'a': 'b', 'c': 'd'} result = utils.unify_labels(labels, None) self.assertEqual(labels, result)
def test_no_labels(self): const_labels = {'a': 'b', 'c': 'd'} result = utils.unify_labels(None, const_labels) self.assertEqual(const_labels, result)