【问题标题】:How can we add our own timestamp in Prometheus metric series?我们如何在 Prometheus 度量系列中添加我们自己的时间戳?
【发布时间】:2026-01-03 09:00:01
【问题描述】:

我正在尝试添加自己的时间戳,而不是 Prometheus 的时间戳。

例如:

node_value{endpoint="https",instance="xx.xx.xx.xx",job="prometheus,node="node1"}

489846 @1610014796.199

489933 @1610014826.199

要求: node_value(above) 是一个具有两个值和时间戳的指标(由普罗米修斯添加的抓取时间戳),而不是抓取时间戳,我想添加我自己从第三方获取的时间戳。我们有这方面的规定吗?

注意:我使用的是 golang prometheus 客户端。

【问题讨论】:

    标签: go prometheus prometheus-operator


    【解决方案1】:

    使用 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
    .
    .
    .
    

    【讨论】:

    • 但请记住,使用除抓取时间戳之外的自定义时间戳可能会引入一堆错误。像那些太旧或太未来的指标一样,Prometheus Server 将删除这些数据。还有一些缺点。
    最近更新 更多