From df145c7e564c8ba0d4722a7a5ab96eb36834e1e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20=C3=81lvarez?= <1671935+kir4h@users.noreply.github.com> Date: Mon, 6 Apr 2020 22:21:01 +0200 Subject: [PATCH] Fix export timestamp not working for prometheus on v2 (#7289) --- .../prometheus_client/prometheus_client.go | 2 +- .../prometheus_client_v2_test.go | 28 +++++++++++++++++++ .../outputs/prometheus_client/v2/collector.go | 7 ++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/plugins/outputs/prometheus_client/prometheus_client.go b/plugins/outputs/prometheus_client/prometheus_client.go index c28ec54ec..57cb1a510 100644 --- a/plugins/outputs/prometheus_client/prometheus_client.go +++ b/plugins/outputs/prometheus_client/prometheus_client.go @@ -139,7 +139,7 @@ func (p *PrometheusClient) Init() error { return err } case 2: - p.collector = v2.NewCollector(p.ExpirationInterval.Duration, p.StringAsLabel) + p.collector = v2.NewCollector(p.ExpirationInterval.Duration, p.StringAsLabel, p.ExportTimestamp) err := registry.Register(p.collector) if err != nil { return err diff --git a/plugins/outputs/prometheus_client/prometheus_client_v2_test.go b/plugins/outputs/prometheus_client/prometheus_client_v2_test.go index 755bd5dc4..3404ab2ed 100644 --- a/plugins/outputs/prometheus_client/prometheus_client_v2_test.go +++ b/plugins/outputs/prometheus_client/prometheus_client_v2_test.go @@ -48,6 +48,34 @@ func TestMetricVersion2(t *testing.T) { # HELP cpu_time_idle Telegraf collected metric # TYPE cpu_time_idle untyped cpu_time_idle{host="example.org"} 42 +`), + }, + { + name: "when export timestamp is true timestamp is present in the metric", + output: &PrometheusClient{ + Listen: ":0", + MetricVersion: 2, + CollectorsExclude: []string{"gocollector", "process"}, + Path: "/metrics", + ExportTimestamp: true, + Log: Logger, + }, + metrics: []telegraf.Metric{ + testutil.MustMetric( + "cpu", + map[string]string{ + "host": "example.org", + }, + map[string]interface{}{ + "time_idle": 42.0, + }, + time.Unix(0, 0), + ), + }, + expected: []byte(` +# HELP cpu_time_idle Telegraf collected metric +# TYPE cpu_time_idle untyped +cpu_time_idle{host="example.org"} 42 0 `), }, { diff --git a/plugins/outputs/prometheus_client/v2/collector.go b/plugins/outputs/prometheus_client/v2/collector.go index 4f8efd839..b28a4deab 100644 --- a/plugins/outputs/prometheus_client/v2/collector.go +++ b/plugins/outputs/prometheus_client/v2/collector.go @@ -43,11 +43,16 @@ type Collector struct { coll *serializer.Collection } -func NewCollector(expire time.Duration, stringsAsLabel bool) *Collector { +func NewCollector(expire time.Duration, stringsAsLabel bool, exportTimestamp bool) *Collector { config := serializer.FormatConfig{} if stringsAsLabel { config.StringHandling = serializer.StringAsLabel } + + if exportTimestamp { + config.TimestampExport = serializer.ExportTimestamp + } + return &Collector{ expireDuration: expire, coll: serializer.NewCollection(config),