簡體   English   中英

將 label 添加到 golang prometheus 收集器

[英]Adding label to golang prometheus collector

我想弄清楚如何將 label 添加到普羅米修斯收集器。 任何想法我在這里缺少什么? 我有兩個文件:main.go 和 collector.go

我使用以下鏈接作為指南。 https://rsmitty.github.io/Prometheus-Exporters/

我模擬了這個例子,所以我可以把它貼在這里。 我最終不會為命令提取“date +%s”。 只是不知道在哪里添加標簽。

對於 label,我正在嘗試添加一個主機名,所以我得到如下結果:

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

我對 golang 也很陌生,所以我很有可能把這一切都弄錯了。 我最終試圖讓普羅米修斯在每次刮擦時提取 cmd 結果。

主要.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))
}

收藏家.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
}

我想到了。 我必須在調用 NewDesc 方法的地方聲明標簽,然后在 MustNewConstMetric 方法中傳遞值

這是我的帶有“主機名”標簽的新“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

github.com/prometheus/client_golang庫使用起來並不簡單。 我建議看一下更簡單的 Go 庫,用於以 Prometheus 格式導出指標 - github.com/VictoriaMetrics/metrics 您可以通過標准 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)
}

然后每次exportCMDResultValue() function 時,相應的cmd_result{host="<hostname>"} <metricValue>指標將導出到/metrics頁面。 /metrics頁面處理程序可以使用以下代碼實現:

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

有關詳細信息,請參閱WritePromtheus function 文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM