From a9ccfe85dcc09abde8d11e96210b2f31fba1671d Mon Sep 17 00:00:00 2001 From: Nicholas Wiersma Date: Fri, 13 Sep 2019 07:24:50 +0200 Subject: [PATCH] Fixed bug with prometheus label names --- prometheus/prometheus.go | 10 +++++----- prometheus/prometheus_test.go | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/prometheus/prometheus.go b/prometheus/prometheus.go index 904346f..17e16e2 100644 --- a/prometheus/prometheus.go +++ b/prometheus/prometheus.go @@ -68,7 +68,7 @@ func (s *Prometheus) Handler() http.Handler { // Inc increments a count by the value. func (s *Prometheus) Inc(name string, value int64, rate float32, tags ...string) { - lblNames, lbls := formatTags(tags) + lblNames, lbls := formatTags(tags, s.fqn) key := createKey(name, lblNames) m, ok := s.counters[key] @@ -99,7 +99,7 @@ func (s *Prometheus) Dec(name string, value int64, rate float32, tags ...string) // Gauge measures the value of a metric. func (s *Prometheus) Gauge(name string, value float64, rate float32, tags ...string) { - lblNames, lbls := formatTags(tags) + lblNames, lbls := formatTags(tags, s.fqn) key := createKey(name, lblNames) m, ok := s.gauges[key] @@ -125,7 +125,7 @@ func (s *Prometheus) Gauge(name string, value float64, rate float32, tags ...str // Timing sends the value of a Duration. func (s *Prometheus) Timing(name string, value time.Duration, rate float32, tags ...string) { - lblNames, lbls := formatTags(tags) + lblNames, lbls := formatTags(tags, s.fqn) key := createKey(name, lblNames) m, ok := s.timings[key] @@ -161,13 +161,13 @@ func createKey(name string, lblNames []string) string { } // formatTags create a prometheus Label map from tags. -func formatTags(t []string) ([]string, prometheus.Labels) { +func formatTags(t []string, fqn *FQN) ([]string, prometheus.Labels) { t = tags.Deduplicate(tags.Normalize(t)) names := make([]string, 0, len(t)/2) lbls := make(prometheus.Labels, len(t)/2) for i := 0; i < len(t); i += 2 { - key := t[i] + key := fqn.Format(t[i]) names = append(names, key) lbls[key] = t[i+1] } diff --git a/prometheus/prometheus_test.go b/prometheus/prometheus_test.go index 40c6a51..e044d30 100644 --- a/prometheus/prometheus_test.go +++ b/prometheus/prometheus_test.go @@ -77,6 +77,20 @@ func TestPrometheus_Timing(t *testing.T) { assert.Contains(t, rr.Body.String(), "test_test_test_count{test=\"test\"} 1") } +func TestPrometheus_ConvertsLabels(t *testing.T) { + l := &testLogger{} + s := prometheus.New("test.test", l) + + s.Inc("test", 2, 1.0, "test-label", "test") + + rr := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/metrics", nil) + s.Handler().ServeHTTP(rr, req) + + assert.Equal(t, "msg=", l.Render()) + assert.Contains(t, rr.Body.String(), "test_test_test{test_label=\"test\"} 2") +} + func TestPrometheus_Close(t *testing.T) { l := &testLogger{} s := prometheus.New("test.test", l)