From da75ecdeacfc67c4929f2cb874a9c536a81a8c07 Mon Sep 17 00:00:00 2001 From: Arianna Vespri Date: Thu, 21 Mar 2024 11:14:49 +0100 Subject: [PATCH] Correct logic in sample naming for counters, add new test Signed-off-by: Arianna Vespri --- expfmt/openmetrics_create.go | 6 ++-- expfmt/openmetrics_create_test.go | 49 +++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/expfmt/openmetrics_create.go b/expfmt/openmetrics_create.go index 432843da..353c5e93 100644 --- a/expfmt/openmetrics_create.go +++ b/expfmt/openmetrics_create.go @@ -248,12 +248,12 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E var createdTsBytesWritten int // Finally the samples, one line for each. + if metricType == dto.MetricType_COUNTER && strings.HasSuffix(name, "_total") { + compliantName = compliantName + "_total" + } for _, metric := range in.Metric { switch metricType { case dto.MetricType_COUNTER: - if strings.HasSuffix(name, "_total") { - compliantName = compliantName + "_total" - } if metric.Counter == nil { return written, fmt.Errorf( "expected counter in metric %s %s", compliantName, metric, diff --git a/expfmt/openmetrics_create_test.go b/expfmt/openmetrics_create_test.go index 4a68eff3..58b284e9 100644 --- a/expfmt/openmetrics_create_test.go +++ b/expfmt/openmetrics_create_test.go @@ -694,6 +694,55 @@ request_duration_microseconds_count 2693 options: []EncoderOption{WithUnit()}, out: `# HELP name doc string # TYPE name counter +`, + }, + // 18: Counter, timestamp given, unit opted in, _total suffix. + { + in: &dto.MetricFamily{ + Name: proto.String("some_measure_total"), + Help: proto.String("some testing measurement"), + Type: dto.MetricType_COUNTER.Enum(), + Unit: proto.String("seconds"), + Metric: []*dto.Metric{ + { + Label: []*dto.LabelPair{ + { + Name: proto.String("labelname"), + Value: proto.String("val1"), + }, + { + Name: proto.String("basename"), + Value: proto.String("basevalue"), + }, + }, + Counter: &dto.Counter{ + Value: proto.Float64(42), + }, + }, + { + Label: []*dto.LabelPair{ + { + Name: proto.String("labelname"), + Value: proto.String("val2"), + }, + { + Name: proto.String("basename"), + Value: proto.String("basevalue"), + }, + }, + Counter: &dto.Counter{ + Value: proto.Float64(.23), + }, + TimestampMs: proto.Int64(1234567890), + }, + }, + }, + options: []EncoderOption{WithUnit()}, + out: `# HELP some_measure_seconds some testing measurement +# TYPE some_measure_seconds counter +# UNIT some_measure_seconds seconds +some_measure_seconds_total{labelname="val1",basename="basevalue"} 42.0 +some_measure_seconds_total{labelname="val2",basename="basevalue"} 0.23 1.23456789e+06 `, }, }