使用 prometheus golang 客户端中提供的NewMetricWithTimestamp 可以做到这一点,但是要公开它,您必须编写一些代码。
首先,您必须编写一个新的 promehetus 收集器来实现 Collector interface,然后提供您的逻辑来为您的指标设置自定义时间戳。
假设我们要使用名为 myCollector 的收集器创建一个具有自定义时间戳的指标 my_metric:
package main
import (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
)
type myCollector struct {
metric *prometheus.Desc
}
func (c *myCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.metric
}
func (c *myCollector) Collect(ch chan<- prometheus.Metric) {
// your logic should be placed here
t := time.Date(2009, time.November, 10, 23, 0, 0, 12345678, time.UTC)
s := prometheus.NewMetricWithTimestamp(t, prometheus.MustNewConstMetric(c.metric, prometheus.CounterValue, 123))
ch <- s
}
func main() {
collector := &myCollector{
metric: prometheus.NewDesc(
"my_metric",
"This is my metric with custom TS",
nil,
nil,
),
}
prometheus.MustRegister(collector)
http.Handle("/metrics", promhttp.Handler())
log.Info("Beginning to serve on port :8080")
http.ListenAndServe(":2112", nil)
}
现在,如果您检查localhost:2112/metrics,您会看到这个,并带有您想要的时间戳:
.
.
.
# HELP my_metric This is my metric with custom TS
# TYPE my_metric counter
my_metric 123 1257894000012
.
.
.