我们如何在 Prometheus 指标系列中添加自己的时间戳?

aks*_*rma 3 go prometheus prometheus-operator

我正在尝试添加我自己的时间戳而不是普罗米修斯的时间戳。

例如:

节点值{端点=“https”,实例=“xx.xx.xx.xx”,作业=“普罗米修斯”,节点=“node1”}

489846@1610014796.199

489933@1610014826.199

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

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

mes*_*ati 7

使用 prometheus golang 客户端中提供的NewMetricWithTimestamp可以实现这一点,但是为了公开它,您必须编写一些代码。

首先,您必须编写一个新的 promehetus 收集器来实现Collector 接口,然后提供逻辑来为指标设置自定义时间戳。

假设我们将my_metric使用名为的收集器创建一个具有自定义时间戳的指标myCollector

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)
}

Run Code Online (Sandbox Code Playgroud)

现在,如果您检查localhost:2112/metrics您看到的内容以及您想要的时间戳:

.
.
.
# HELP my_metric This is my metric with custom TS
# TYPE my_metric counter
my_metric 123 1257894000012
.
.
.
Run Code Online (Sandbox Code Playgroud)

  • 但请记住,使用除抓取时间戳之外的自定义时间戳可能会引入一堆错误。就像太旧的指标或太未来的数据一样,Prometheus 服务器将丢弃它们。还有一些缺点。 (2认同)