2

我开始使用 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))
}

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

4

2 回答 2

3

这是自定义收集器的示例(来自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())
于 2018-09-19T07:27:56.060 回答
1

您可能想要实现一个收集器,并在 Prometheus 服务器抓取时运行 http 请求。查看最佳实践

在为您的导出器实现收集器时,您永远不应该使用通常的直接检测方法,然后在每次抓取时更新指标。

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

于 2018-02-22T14:34:38.797 回答