登录
首页 >  Golang >  Go问答

prometheus中如何查找特定指标的所有时间序列数据?

来源:stackoverflow

时间:2024-02-11 09:45:26 272浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《prometheus中如何查找特定指标的所有时间序列数据?》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

如何在prometheus中无步骤查询指定指标的原始时间序列值?例如,我想查询1分钟内实际有多少个数据点,但是当我指定step为15s时,无论数据点有多少,都会生成4个结果

package main

import (
    "context"
    "fmt"
    "github.com/prometheus/client_golang/api"
    v1 "github.com/prometheus/client_golang/api/prometheus/v1"
    "log"
    "time"
)

var (
    prometheus string        = "http://10.22.5.54:8481/select/0/prometheus"
    timeout    time.Duration = time.Second * 30
)

func main() {

    client, err := api.NewClient(api.Config{Address: prometheus})
    if err != nil {
        log.Fatalln("Error connect to the prometheus: ", err)
    }

    v1api := v1.NewAPI(client)
    ctx, cancel := context.WithTimeout(context.Background(), timeout)
    defer cancel()

    result, warnings, err := v1api.QueryRange(ctx, "up{app=\"activity-api\"}", v1.Range{Start: time.Now().Add(-time.Minute * 1), End: time.Now(), Step: time.Second * 15})

    if err != nil {
        log.Printf("Error querying Prometheus: %s\n", err)
    }
    if len(warnings) > 0 {
        log.Printf("Warnings: %s", warnings)
    }

    fmt.Println(result)
}

正确答案


您需要使用 v1api.query 而不是 v1api.queryrange,并在 series selector 末尾的方括号中添加所需的间隔。例如,以下查询应返回匹配 up{app="activity 的时间序列的原始样本-api"} 在给定的 time 处结束的最后 15 秒。

t := time.now()
result, warnings, err := v1api.query(ctx, `up{app="activity-api"}[15s]`, t)

查看更多详情here

在内部,github.com/prometheus/client_golang 包仅查询 /api/v1/query http 端点,因此向此端点发出 http 请求可能更容易,而无需弄清楚如何使用 github.com/prometheus/client_golang。例如,以下命令将从 victoriametrics 集群返回原始样本:

curl http://10.22.5.54:8481/select/0/prometheus/api/v1/query -d 'up{app="activity-api"}[15s]'

victoriametrics 还提供了 APIs for exporting raw samples

另请参阅 https://valyala.medium.com/analyzing-prometheus-data-with-external-tools-5f3e5e147639

理论要掌握,实操不能落!以上关于《prometheus中如何查找特定指标的所有时间序列数据?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>