猿问

如何解析普罗米修斯数据

我已经能够通过发送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这样的串联格式。

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

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


哔哔one
浏览 189回答 1
1回答

慕工程0101907

已经有一个很好的软件包可以做到这一点,它是由普罗米修斯的作者自己完成的。他们编写了一堆Go库,这些库在Prometheus组件和库之间共享。它们被认为是普罗米修斯的内部,但你可以使用它们。请参阅:github.com/prometheus/common 文档。有一个名为“普罗米修斯”的软件包可以解码和编码普罗米修斯的Exposition Format(Link)。是的,它遵循EBNF语法,因此也可以使用包,但是您开箱即用。expfmtebnfexpfmt使用的软件包:expfmt示例输入:# HELP net_conntrack_dialer_conn_attempted_total# TYPE net_conntrack_dialer_conn_attempted_total untypednet_conntrack_dialer_conn_attempted_total{dialer_name="federate",instance="localhost:9090",job="prometheus"} 1 1608520832877示例程序:package mainimport (&nbsp; &nbsp; "flag"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "os"&nbsp; &nbsp; dto "github.com/prometheus/client_model/go"&nbsp; &nbsp; "github.com/prometheus/common/expfmt")func fatal(err error) {&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }}func parseMF(path string) (map[string]*dto.MetricFamily, error) {&nbsp; &nbsp; reader, err := os.Open(path)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; var parser expfmt.TextParser&nbsp; &nbsp; mf, err := parser.TextToMetricFamilies(reader)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; return mf, nil}func main() {&nbsp; &nbsp; f := flag.String("f", "", "set filepath")&nbsp; &nbsp; flag.Parse()&nbsp; &nbsp; mf, err := parseMF(*f)&nbsp; &nbsp; fatal(err)&nbsp; &nbsp; for k, v := range mf {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("KEY: ", k)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("VAL: ", v)&nbsp; &nbsp; }}示例输出:KEY:&nbsp; net_conntrack_dialer_conn_attempted_totalVAL:&nbsp; name:"net_conntrack_dialer_conn_attempted_total" type:UNTYPED metric:<label:<name:"dialer_name" value:"federate" > label:<name:"instance" value:"localhost:9090" > label:<name:"job" value:"prometheus" > untyped:<value:1 > timestamp_ms:1608520832877 >因此,对于您的用例来说,这是一个不错的选择。expfmt更新:OP发布的输入中的格式问题:指:https://github.com/prometheus/pushgateway/issues/147#issuecomment-368215305https://github.com/prometheus/pushgateway#command-lineNote that in the text protocol, each line has to end with a line-feedcharacter (aka 'LF' or '\n'). Ending a line in other ways, e.g. with&nbsp;'CR' aka '\r', 'CRLF' aka '\r\n', or just the end of the packet, willresult in a protocol error.但是从错误消息中,我可以看到char存在于put中,这在设计上是不可接受的。因此,用于行尾。\r\n
随时随地看视频慕课网APP

相关分类

Go
我要回答