Go语言 为戈兰普罗米修斯采集器添加标签

qni6mghb  于 2023-02-17  发布在  Go
关注(0)|答案(2)|浏览(175)

我正在想办法给普罗米修斯收集器加个标签。你知道我漏掉了什么吗?我有两个文件:主,去收集器,去
我使用以下链接作为指导。https://rsmitty.github.io/Prometheus-Exporters/
我模拟了这个例子,所以我可以把它贴在这里。我最终不会为命令提取“date +%s”。只是不知道在哪里添加标签。
对于标签,我尝试添加一个主机名,因此得到如下结果:

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

我也是刚到golang,所以很有可能我的做法是完全错误的!我最终试图让prometheus在每次刮伤时都能得到cmd结果。

主频道,开始

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))
}

收藏家,开始

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
}
z2acfund

z2acfund1#

我明白了,我必须声明调用NewDesc方法的标签,然后在MustNewConstMetric方法中传递值
下面是带有“hostname”标签的新“newCollector”。

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

值得注意的是,这里我只添加了“变量标签”,最后一个“nil”是常量标签。
您可以添加任意数量的项目,如下所示...

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

这是涵盖在这里:https://godoc.org/github.com/prometheus/client_golang/prometheus#NewDesc
接下来,我可以在调用“MustNewConstMetric”方法时添加这些值。

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

整个街区...

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)

}

如果我传入多个标签;比如我上面的例子,它看起来更像这样...

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

这是涵盖在这里:https://godoc.org/github.com/prometheus/client_golang/prometheus#MustNewConstMetric

ippsafx7

ippsafx72#

github.com/prometheus/client_golang库使用起来并不简单,我建议看一看更简单的Go语言库,它可以导出Prometheus格式的指标-github.com/VictoriaMetrics/metrics,通过标准Go语言库中的fmt.Sprintf()函数,可以轻松地指定任意数量的动态标签:

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

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

然后,每次调用exportCMDResultValue()函数时,将在/metrics页导出相应的cmd_result{host="<hostname>"} <metricValue>度量。/metrics页处理程序可以使用以下代码实现:

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

详见WritePrometheus函数文档。

相关问题