简体   繁体   English

将 label 添加到 golang prometheus 收集器

[英]Adding label to golang prometheus collector

I'm trying to figure out how to add a label to a prometheus collector.我想弄清楚如何将 label 添加到普罗米修斯收集器。 Any ideas what I'm missing here?任何想法我在这里缺少什么? I have two files: main.go and collector.go我有两个文件:main.go 和 collector.go

I used the following link as a guide.我使用以下链接作为指南。 https://rsmitty.github.io/Prometheus-Exporters/ https://rsmitty.github.io/Prometheus-Exporters/

I mocked up this example, so I could post it here.我模拟了这个例子,所以我可以把它贴在这里。 I'm ultimately not going to pull "date +%s" for the command.我最终不会为命令提取“date +%s”。 Just can't figure out where to add labels.只是不知道在哪里添加标签。

For the label I'm trying to add a hostname, so I have a result like:对于 label,我正在尝试添加一个主机名,所以我得到如下结果:

# HELP cmd_result Shows the cmd result
# TYPE cmd_result gauge
cmd_result{host="my_device_hostname"} 1.919256141363144e-76

I'm also really new to golang, so there is a good chance I'm going about this all wrong.我对 golang 也很陌生,所以我很有可能把这一切都弄错了。 I'm ultimately trying to get prometheus to pull the cmd result on each scrape.我最终试图让普罗米修斯在每次刮擦时提取 cmd 结果。

main.go主要.go

package main

import (
    "net/http"

    log "github.com/Sirupsen/logrus"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {

    //Create a new instance of the collector and
    //register it with the prometheus client.
    cmd := newCollector()
    prometheus.MustRegister(cmd)

    //This section will start the HTTP server and expose
    //any metrics on the /metrics endpoint.
    http.Handle("/metrics", promhttp.Handler())
    log.Info("Beginning to serve on port :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

collector.go收藏家.go

package main

import (
    "encoding/binary"
    "fmt"
    "math"
    "os/exec"
    "strings"

    "github.com/prometheus/client_golang/prometheus"
)

type cmdCollector struct {
    cmdMetric *prometheus.Desc
}

func newCollector() *cmdCollector {
    return &cmdCollector{
        cmdMetric: prometheus.NewDesc("cmd_result",
            "Shows the cmd result",
            nil, nil,
        ),
    }
}

func (collector *cmdCollector) Describe(ch chan<- *prometheus.Desc) {
    ch <- collector.cmdMetric
}

func (collector *cmdCollector) Collect(ch chan<- prometheus.Metric) {

    var metricValue float64
    command := string("date +%s")
    cmdResult := exeCmd(command)
    metricValue = cmdResult

    ch <- prometheus.MustNewConstMetric(collector.cmdMetric, prometheus.GaugeValue, metricValue)

}

func exeCmd(cmd string) float64 {
    parts := strings.Fields(cmd)
    out, err := exec.Command(parts[0], parts[1]).Output()
    if err != nil {
        fmt.Println("error occured")
        fmt.Printf("%s", err)
    }
    cmdProcessResult := Float64frombytes(out)
    return cmdProcessResult
}

func Float64frombytes(bytes []byte) float64 {
    bits := binary.LittleEndian.Uint64(bytes)
    float := math.Float64frombits(bits)
    return float
}

I figured it out.我想到了。 I had to declare the label where I was calling the NewDesc method and then pass the value within the MustNewConstMetric method我必须在调用 NewDesc 方法的地方声明标签,然后在 MustNewConstMetric 方法中传递值

Here is my new "newCollector" with the "hostname" label.这是我的带有“主机名”标签的新“newCollector”。

func newCollector() *cmdCollector {
    return &cmdCollector{
        cmdMetric: prometheus.NewDesc("cmd_result",
            "Shows the cmd result",
            []string{"hostname"}, nil,
        ),
    }
}

It's worth noting that I'm only adding "variable labels" here.值得注意的是,我只是在这里添加了“变量标签”。 That last 'nil' is for constant labels.最后一个 'nil' 用于常量标签。

You can add any number of items like so...您可以添加任意数量的项目,例如...

[]string{"hostname", "another_label", "and_another_label"}

This is covered here: https://godoc.org/github.com/prometheus/client_golang/prometheus#NewDesc此处涵盖: https : //godoc.org/github.com/prometheus/client_golang/prometheus#NewDesc

Next I can add those values when calling the "MustNewConstMetric" method.接下来,我可以在调用“MustNewConstMetric”方法时添加这些值。

ch <- prometheus.MustNewConstMetric(collector.cmdMetric, prometheus.GaugeValue, metricValue, hostname)

The whole block...整个街区...

func (collector *cmdCollector) Collect(ch chan<- prometheus.Metric) {

    var metricValue float64
    command := string("date +%s")
    cmdResult := exeCmd(command)
    metricValue = cmdResult

    ch <- prometheus.MustNewConstMetric(collector.cmdMetric, prometheus.GaugeValue, metricValue, hostname)

}

If I was passing in multiple labels;如果我传入多个标签; such as my example above, it would look more like this...比如我上面的例子,它看起来更像这样......

ch <- prometheus.MustNewConstMetric(collector.cmdMetric, prometheus.GaugeValue, metricValue, hostname, anotherLabel", "andAnotherLabel)

This is covered here: https://godoc.org/github.com/prometheus/client_golang/prometheus#MustNewConstMetric此处涵盖: https : //godoc.org/github.com/prometheus/client_golang/prometheus#MustNewConstMetric

The github.com/prometheus/client_golang library is non-trivial to use. github.com/prometheus/client_golang库使用起来并不简单。 I'd suggest taking a look at much simpler Go library for exporting metrics in Prometheus format - github.com/VictoriaMetrics/metrics .我建议看一下更简单的 Go 库,用于以 Prometheus 格式导出指标 - github.com/VictoriaMetrics/metrics You can easily specify arbitrary number of dynamic labels via fmt.Sprintf() function from standard Go library:您可以通过标准 Go 库中的fmt.Sprintf() function 轻松指定任意数量的动态标签:

import (
  "github.com/VictoriaMetrics/metrics"
)

func exportCMDResultValue(hostname string, metricValue float64) {
  metricName := fmt.Sprintf("cmd_result{host=%q}", hostname)
  metrics.GetOrCreateFloatCounter(metricName).Set(metricValue)
}

Then the corresponding cmd_result{host="<hostname>"} <metricValue> metric will be exported at /metrics page each time exportCMDResultValue() function is called.然后每次exportCMDResultValue() function 时,相应的cmd_result{host="<hostname>"} <metricValue>指标将导出到/metrics页面。 The /metrics page handler can be implemented with the following code: /metrics页面处理程序可以使用以下代码实现:

http.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) {
    metrics.WritePrometheus(w, false)
})

See WritePromtheus function docs for details.有关详细信息,请参阅WritePromtheus function 文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM