如何在 golang 中将直方图添加到 prometheus 导出器?
Posted
技术标签:
【中文标题】如何在 golang 中将直方图添加到 prometheus 导出器?【英文标题】:How do I add histogram to prometheus exporter in golang? 【发布时间】:2021-11-28 22:25:32 【问题描述】:这是我的代码示例。现在我想在我的代码中添加直方图。 但我找不到像这样添加直方图的方法。
有人可以帮我吗? 我可以编写直方图示例,但无法在下面的代码中添加它
package main
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"net/http"
)
type fooCollector struct
fooMetric *prometheus.Desc
func newFooCollector(label1 string) *fooCollector
return &fooCollector
fooMetric: prometheus.NewDesc("fff_metric",
"Shows whether a foo has occurred in our cluster",
nil, prometheus.Labels"env":label1,
),
func (collector *fooCollector) Describe(ch chan<- *prometheus.Desc)
//Update this section with the each metric you create for a given collector
ch <- collector.fooMetric
func (collector *fooCollector) Collect(ch chan<- prometheus.Metric)
ch <- prometheus.MustNewConstMetric(collector.fooMetric, prometheus.GaugeValue, 111111)
func main()
prometheus.MustRegister(newFooCollector("dev"))
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":80", nil)
【问题讨论】:
【参考方案1】:我终于学会了直方图的工作原理。这是我的代码
package main
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)
type fooCollector struct
fooMetric *prometheus.Desc
//First,we define the variable of histogram
var (
hbrms_histovec = prometheus.NewHistogramVec(
prometheus.HistogramOpts
Name: "hbrms_histogram",
Help: "hbrms_histogram",
ConstLabels: prometheus.Labels"constname": "constvalue",
Buckets: prometheus.ExponentialBuckets(50, 1.3, 15),//50*1.3,15times
,
[]string"env",
)
)
func newFooCollector() *fooCollector
return &fooCollector
fooMetric: prometheus.NewDesc("fff_metric",
"Shows whether a foo has occurred in our cluster",
nil, nil,
),
func (collector *fooCollector) Describe(ch chan<- *prometheus.Desc)
ch <- collector.fooMetric
func (collector *fooCollector) Collect(ch chan<- prometheus.Metric)
ch <- prometheus.MustNewConstMetric(collector.fooMetric, prometheus.CounterValue, float64(1))
// 2nd,we set metrics in this way instead of write to channel,we just find a way of calling the code below when we visit the url.
hbrms_histovec.WithLabelValues("val1").Observe(float64(10))
func main()
reg := prometheus.NewPedanticRegistry()
reg.MustRegister(newFooCollector())
// finally,we register the metrics "hbrms_histovec" in this way
reg.MustRegister(hbrms_histovec)
gatherers := prometheus.Gatherersreg
h := promhttp.HandlerFor(gatherers,
promhttp.HandlerOpts
ErrorHandling: promhttp.ContinueOnError,
)
http.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request)
h.ServeHTTP(w, r)
)
http.ListenAndServe(":80", nil)
【讨论】:
以上是关于如何在 golang 中将直方图添加到 prometheus 导出器?的主要内容,如果未能解决你的问题,请参考以下文章
如何在golang中将字节附加到字节数组?不是字节数组到字节数组切片等[重复]
发送连接升级后,如何在golang中将客户端http连接升级到websockets
如何在Golang beego框架中将数据从MySQL数据库保存到redis?