如何更新prometheus导出器中的度量值(golang)

时间:2018-02-22 14:25:48

标签: go prometheus exporter

我开始使用golang编写自己的prometheus导出器。 我认为我掌握了基础知识,但我不知道该做些什么来使公制的价值更新。使用Set只执行一次。 它在运行时没有改变。

到目前为止我所拥有的:

package main

import (
  "log"
  "net/http"

  "github.com/prometheus/client_golang/prometheus"
  "github.com/prometheus/client_golang/prometheus/promhttp"

  "time"
  "io/ioutil"
  "github.com/tidwall/gjson"
  "strconv"
)

var (
  sidekiqProcessed = setGaugeMetric("sidekiq_processed", "Sidekiq Processed", "lable", "lablevalue")
)

func setGaugeMetric(name string, help string, label string, labelvalue string) (prometheusGauge prometheus.Gauge) {
  var (
    gaugeMetric = prometheus.NewGauge(prometheus.GaugeOpts{
      Name: name,
      Help: help,
      ConstLabels: prometheus.Labels{label: labelvalue},
    })
  )

  return gaugeMetric
}

func getSidekiqProcessed() (sidekiq float64) {
  body := getContent("http://example.com/sidekiq/stats")
  processed := gjson.Get(body, "sidekiq.processed")
  conv, err := strconv.ParseFloat(processed.String(), 64)
  if err != nil {
    log.Fatal(err)
  }
  return conv
}

func getContent(url string) (body string) {
  httpClient := &http.Client{Timeout: 10 * time.Second}
  res, err := httpClient.Get(url)

  if err != nil {
    log.Fatal(err)
  }

  content, err := ioutil.ReadAll(res.Body)
  res.Body.Close()

  if err != nil {
    log.Fatal(err)
  }

  return string(content)
}

func init() {
  prometheus.MustRegister(sidekiqProcessed)
}

func main() {
  sidekiqProcessed.Set(getSidekiqProcessed())

  // The Handler function provides a default handler to expose metrics
  // via an HTTP server. "/metrics" is the usual endpoint for that.
  http.Handle("/metrics", promhttp.Handler())
  log.Fatal(http.ListenAndServe(":8080", nil))
}

阅读有关收集器的内容,但不知道如何实现它。 有人可以帮我完成/更正我的代码,以便度量值也在运行时更新吗?

2 个答案:

答案 0 :(得分:1)

您可能希望实现收集器,并在Prometheus服务器擦除时运行http请求。 See the best practices

  

为导出器实现收集器时,不应使用通常的直接检测方法,然后更新每次扫描的指标。

     

每次都要创建新指标。在Go中,这是使用Update()方法中的MustNewConstMetric完成的。对于Python,请参阅https://github.com/prometheus/client_python#custom-collectors,对于Java在collect方法中生成List,请参阅StandardExports.java以获取示例。

答案 1 :(得分:1)

以下是自定义收集器的一个示例(来自https://www.robustperception.io/setting-a-prometheus-counter):

package main

import "github.com/prometheus/client_golang/prometheus"

type MyCollector struct {
  counterDesc *prometheus.Desc
}

func (c *MyCollector) Describe(ch chan<- *prometheus.Desc) {
  ch <- c.counterDesc
}

func (c *MyCollector) Collect(ch chan<- prometheus.Metric) {
  value := 1.0 // Your code to fetch the counter value goes here.
  ch <- prometheus.MustNewConstMetric(
    c.counterDesc,
    prometheus.CounterValue,
    value,
  )
}

func NewMyCollector() *MyCollector {
  return &MyCollector{
    counterDesc: prometheus.NewDesc("my_counter_total", "Help string", nil, nil),
  }
}

// To hook in the collector: prometheus.MustRegister(NewMyCollector())