使用go自定义prometheus监控指标
package main
import (
"fmt"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"log"
"math/rand"
"time"
)
var (
counter = prometheus.NewCounter(
prometheus.CounterOpts{
Namespace: "golang",
Name: "my_counter",
Help: "This is my counter",
})
gauge = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: "golang",
Name: "my_gauge",
Help: "This is my gauge",
ConstLabels: map[string]string{
"path":"/api/test",
},
})
gauge2 = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: "golang",
Name: "my_gauge",
Help: "This is my gauge",
ConstLabels: map[string]string{
"path":"/api/test1",
},
})
gauge3 = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: "golang",
Name: "my_gauge",
Help: "This is my gauge",
ConstLabels: map[string]string{
"path":"/api/test2",
},
})
gauge4 = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: "golang",
Name: "my_gauge",
Help: "This is my gauge",
ConstLabels: map[string]string{
"path":"/api/test3",
},
})
histogram = prometheus.NewHistogram(
prometheus.HistogramOpts{
Namespace: "golang",
Name: "my_histogram",
Help: "This is my histogram",
})
summary = prometheus.NewSummary(
prometheus.SummaryOpts{
Namespace: "golang",
Name: "my_summary",
Help: "This is my summary",
})
)
func main() {
rand.Seed(time.Now().Unix())
http.Handle("/metrics", promhttp.Handler())
prometheus.MustRegister(counter)
prometheus.MustRegister(gauge)
prometheus.MustRegister(gauge2)
prometheus.MustRegister(gauge3)
prometheus.MustRegister(gauge4)
prometheus.MustRegister(histogram)
prometheus.MustRegister(summary)
go func() {
for {
counter.Add(rand.Float64() * 5)
gauge.Set(rand.Float64()*15 )
gauge2.Set(rand.Float64()*15 )
gauge3.Set(rand.Float64()*15 )
gauge4.Set(rand.Float64()*15 )
histogram.Observe(rand.Float64() * 10)
summary.Observe(rand.Float64() * 10)
time.Sleep(time.Second)
}
}()
fmt.Println("Starting.....")
log.Fatal(http.ListenAndServe(":8080", nil))
}