prometheus 自己实现exporter

1.  看源代码可以发现Collector 接口定义了两个方法,实现这两个方法就可以暴露数据了。

 

 

2. 示列代码

package main

import (
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"github.com/prometheus/client_golang/prometheus"
)

type fooCollector struct {
fooMetric *prometheus.Desc
barMetric *prometheus.Desc
}


func newFooCollector() *fooCollector {
m1 := make(map[string]string)
m1["env"] = "prod"
v := []string{"hostname"}
return &fooCollector{
fooMetric: prometheus.NewDesc("fff_metrics","Show metrics a for mysql",nil,nil),
barMetric:prometheus.NewDesc("bbb_metrics","Show metrics a bar occu",v,m1),
}
}

func (collect *fooCollector) Describe(ch chan <- *prometheus.Desc) {
ch <- collect.barMetric
ch <- collect.fooMetric

}

func (collect *fooCollector) Collect(ch chan<- prometheus.Metric) {
var metricValue float64

if 1 == 1 {
metricValue = 1
}


ch <- prometheus.MustNewConstMetric(collect.fooMetric,prometheus.GaugeValue, metricValue)
ch <- prometheus.MustNewConstMetric(collect.barMetric,prometheus.CounterValue, metricValue,"kk")
}


func main() {
foo := newFooCollector()
prometheus.MustRegister(foo)
log.Info("beging to server on Port: 18080")
http.Handle("/metrics",promhttp.Handler())
log.Fatal(http.ListenAndServe(":18080",nil))
}


# 一个变量label, 一个是常量label.

  

posted @ 2019-03-18 15:02  追求那份真  阅读(4645)  评论(0编辑  收藏  举报