登录
首页 >  Golang >  Go问答

分析Prometheus数据的方法

来源:stackoverflow

时间:2024-03-05 15:09:24 346浏览 收藏

从现在开始,努力学习吧!本文《分析Prometheus数据的方法》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我已经能够通过发送 http get 来获取指标,如下所示:

# TYPE net_conntrack_dialer_conn_attempted_total untyped net_conntrack_dialer_conn_attempted_total{dialer_name="federate",instance="localhost:9090",job="prometheus"} 1 1608520832877

现在我需要解析这些数据并获得对每条数据的控制权,以便我可以转换像json这样的tand格式。

我一直在研究go中的ebnf包: ebnf 包

有人能给我指出解析上述数据的正确方向吗?


解决方案


已经有一个很好的包可以做到这一点,它是由 prometheus 的作者本身编写的。

他们编写了一堆在 prometheus 组件和库之间共享的 go 库。它们被认为是 prometheus 内部的,但您可以使用它们。

参考:github.com/prometheus/common 文档。有一个名为 expfmt 的软件包可以对 prometheus's exposition format 进行解码和编码 (Link)。是的,它遵循 ebnf 语法,因此也可以使用 ebnf 包,但您可以直接使用 expfmt

使用的包:expfmt

示例输入:

# help net_conntrack_dialer_conn_attempted_total
# type net_conntrack_dialer_conn_attempted_total untyped
net_conntrack_dialer_conn_attempted_total{dialer_name="federate",instance="localhost:9090",job="prometheus"} 1 1608520832877

示例程序:

package main

import (
    "flag"
    "fmt"
    "log"
    "os"

    dto "github.com/prometheus/client_model/go"
    "github.com/prometheus/common/expfmt"
)

func fatal(err error) {
    if err != nil {
        log.fatalln(err)
    }
}

func parsemf(path string) (map[string]*dto.metricfamily, error) {
    reader, err := os.open(path)
    if err != nil {
        return nil, err
    }

    var parser expfmt.textparser
    mf, err := parser.texttometricfamilies(reader)
    if err != nil {
        return nil, err
    }
    return mf, nil
}

func main() {
    f := flag.string("f", "", "set filepath")
    flag.parse()

    mf, err := parsemf(*f)
    fatal(err)

    for k, v := range mf {
        fmt.println("key: ", k)
        fmt.println("val: ", v)
    }
}

示例输出:

key:  net_conntrack_dialer_conn_attempted_total
val:  name:"net_conntrack_dialer_conn_attempted_total" type:untyped metric: label: label: untyped: timestamp_ms:1608520832877 >

因此,expfmt 是适合您的用例的不错选择。

更新:op 发布的输入中存在格式问题:

参考:

  1. https://github.com/prometheus/pushgateway/issues/147#issuecomment-368215305

  2. https://github.com/prometheus/pushgateway#command-line

Note that in the text protocol, each line has to end with a line-feed
character (aka 'LF' or '\n'). Ending a line in other ways, e.g. with 
'CR' aka '\r', 'CRLF' aka '\r\n', or just the end of the packet, will
result in a protocol error.

但是从错误消息中,我可以看到 \r 字符存在于 put 中,这是设计上不可接受的。因此使用 \n 作为行结尾。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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