[示例]使用GoLang編寫prometheus-exporter
package prometheus
import (
? "github.com/prometheus/client_golang/prometheus"
? "github.com/prometheus/client_golang/prometheus/promhttp"
? "math/rand"
? "net/http"
)
type ExporterCollector struct {
? JobCountDesc *prometheus.Desc
}
// 實現(xiàn) prometheus.Collector 接口
func (c *ExporterCollector) Describe(ch chan<- *prometheus.Desc) {
? ch <- c.JobCountDesc //傳入隊列中
}
// 自定義的方法,僅僅是生成數(shù)據(jù)
func (c *ExporterCollector) GetData() (JobCount map[string]float64) {
? JobCount = make(map[string]float64)
? JobCount["root"] = float64(rand.Intn(233))
? JobCount["user01"] = float64(rand.Intn(233))
? return
}
// 實現(xiàn) prometheus.Collector 接口
func (c *ExporterCollector) Collect(ch chan<- prometheus.Metric) {
? JobCount := c.GetData()
? for userName, value := range JobCount {
? ? ?ch <- prometheus.MustNewConstMetric(
? ? ? ? c.JobCountDesc,
? ? ? ? prometheus.GaugeValue, //設(shè)置數(shù)據(jù)類型 CounterValue GaugeValue UntypedValue
? ? ? ? value,
? ? ? ? userName,
? ? ?)
? }
}
func NewClusterManager() *ExporterCollector {
? return &ExporterCollector{
? ? ?JobCountDesc: prometheus.NewDesc(
? ? ? ? "job_count", ? ? ? ? ? //指標名稱
? ? ? ? "統(tǒng)計數(shù)據(jù)", ? ? ? ? ? ? ? ?//指標說明
? ? ? ? []string{"user_name"}, //這里與Collect中value后面的數(shù)值
? ? ? ? prometheus.Labels{}, ? //標簽可以設(shè)置
? ? ?),
? }
}
//可以通過這個方法獲取Handler,之后與和web框架整合
func GetExporterHandler() http.Handler {
? data := NewClusterManager()
? reg := prometheus.NewPedanticRegistry()
? reg.MustRegister(data)
? gatherers := prometheus.Gatherers{
? ? ?prometheus.DefaultGatherer,
? ? ?reg,
? }
? h := promhttp.HandlerFor(gatherers,
? ? ?promhttp.HandlerOpts{
? ? ? ? ErrorHandling: promhttp.ContinueOnError,
? ? ?})
? return h
}