在 Go 中提取 Prometheus 指标

Mat*_*a_V 2 go prometheus

我是 Golang 的新手,我想要做的是查询 Prometheus 并将查询结果保存在一个对象(例如地图)中,该对象具有所有时间戳及其度量值。我从这个示例代码开始,只做了一些更改(https://github.com/prometheus/client_golang/blob/master/api/prometheus/v1/example_test.go

func getFromPromRange(start time.Time, end time.Time, metric string) model.Value {
    client, err := api.NewClient(api.Config{
        Address: "http://localhost:9090",
    })
    if err != nil {
        fmt.Printf("Error creating client: %v\n", err)
        os.Exit(1)
    }
    v1api := v1.NewAPI(client)
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    r := v1.Range{
        Start: start,
        End:   end,
        Step:  time.Second,
    }
    result, warnings, err := v1api.QueryRange(ctx, metric, r) 
    if err != nil {
        fmt.Printf("Error querying Prometheus: %v\n", err)
        os.Exit(1)
    }
    if len(warnings) > 0 {
        fmt.Printf("Warnings: %v\n", warnings)
    }
    fmt.Printf("Result:\n%v\n", result)

    return result
}
Run Code Online (Sandbox Code Playgroud)

打印的结果例如: "TEST{instance="localhost:4321", job="realtime"} =>\n21 @[1597758502.337]\n22 @[1597758503.337]...

这些实际上是 Prometheus 上的正确值和时间戳。如何将这些时间戳和值插入到地图对象(或我可以在代码中使用的其他类型的对象)中?

小智 6

来自结果QueryRange的类型为model.Matrix

这将包含一个类型为 的指针*SampleStream。由于您的示例仅包含一个 SampleStream,我们可以直接访问第一个。

SampleStream 然后有一个MetricandValues类型[]SamplePair。您的目标是样本对的切片。然后我们可以迭代并构建例如地图。

mapData := make(map[model.Time]model.SampleValue)

for _, val := range result.(model.Matrix)[0].Values {
    mapData[val.Timestamp] = val.Value
}

fmt.Println(mapData)
Run Code Online (Sandbox Code Playgroud)


小智 0

您必须知道返回的结果类型。例如,model.Value 可以是标量、向量、矩阵或字符串类型。每种类型都有自己的获取数据和时间戳的方式。例如,Vector 具有 Sample 类型的数组,其中包含您要查找的数据。如果您想深入了解,godocs 和 prom/go 客户端的 github 存储库有非常好的文档。