From 7ef88c4bf9378ba295bf74da5e35a85aa534cc73 Mon Sep 17 00:00:00 2001 From: Daniel Nelson Date: Wed, 18 Oct 2017 17:42:30 -0700 Subject: [PATCH] Use labels in prometheus output for string fields (#3350) --- .../prometheus_client/prometheus_client.go | 9 ++++++ .../prometheus_client_test.go | 28 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/plugins/outputs/prometheus_client/prometheus_client.go b/plugins/outputs/prometheus_client/prometheus_client.go index 48b625513..d7702a062 100644 --- a/plugins/outputs/prometheus_client/prometheus_client.go +++ b/plugins/outputs/prometheus_client/prometheus_client.go @@ -242,6 +242,15 @@ func (p *PrometheusClient) Write(metrics []telegraf.Metric) error { labels[sanitize(k)] = v } + // Prometheus doesn't have a string value type, so convert string + // fields to labels. + for fn, fv := range point.Fields() { + switch fv := fv.(type) { + case string: + labels[sanitize(fn)] = fv + } + } + for fn, fv := range point.Fields() { // Ignore string and bool fields. var value float64 diff --git a/plugins/outputs/prometheus_client/prometheus_client_test.go b/plugins/outputs/prometheus_client/prometheus_client_test.go index a997c0401..1bb1cc83a 100644 --- a/plugins/outputs/prometheus_client/prometheus_client_test.go +++ b/plugins/outputs/prometheus_client/prometheus_client_test.go @@ -324,6 +324,34 @@ func TestWrite_Tags(t *testing.T) { require.True(t, now.Before(sample2.Expiration)) } +func TestWrite_StringFields(t *testing.T) { + now := time.Now() + p1, err := metric.New( + "foo", + make(map[string]string), + map[string]interface{}{"value": 1.0, "status": "good"}, + now, + telegraf.Counter) + p2, err := metric.New( + "bar", + make(map[string]string), + map[string]interface{}{"status": "needs numeric field"}, + now, + telegraf.Gauge) + var metrics = []telegraf.Metric{p1, p2} + + client := NewClient() + err = client.Write(metrics) + require.NoError(t, err) + + fam, ok := client.fam["foo"] + require.True(t, ok) + require.Equal(t, 1, fam.LabelSet["status"]) + + fam, ok = client.fam["bar"] + require.False(t, ok) +} + func TestExpire(t *testing.T) { client := NewClient()