-
Notifications
You must be signed in to change notification settings - Fork 2
/
prometheus.go
79 lines (64 loc) · 2.01 KB
/
prometheus.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package zmetrics
import (
"fmt"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
"net/http"
)
type PrometheusCollector prometheus.Collector
type CounterOpts prometheus.CounterOpts
type GaugeOpts prometheus.GaugeOpts
type HistogramOpts prometheus.HistogramOpts
type Counter prometheus.Counter
type CounterVec *prometheus.CounterVec
type Gauge prometheus.Gauge
type Histogram prometheus.Histogram
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func newResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{w, http.StatusOK}
}
func prometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rw := newResponseWriter(w)
next.ServeHTTP(rw, r)
})
}
// StartMetricsServer starts a prometheus server.
// Data Url is at localhost:<port>/metrics/<endpoint>
func StartMetricsServer(port string, endpoint string) chan error {
router := mux.NewRouter()
router.Use(prometheusMiddleware)
// Prometheus endpoint
router.Path("/metrics/" + endpoint).Handler(promhttp.Handler())
errChan := make(chan error)
go func() {
err := http.ListenAndServe(fmt.Sprintf(":%s", port), router)
if err != nil {
zap.S().Errorf("Prometheus server error: %v", err)
errChan <- err
} else {
zap.S().Infof("Prometheus server serving at port %s", port)
}
}()
return errChan
}
func RegisterMetric(c PrometheusCollector) error {
return prometheus.Register(c)
}
func NewSimpleCounter(opts CounterOpts) Counter {
return prometheus.NewCounter(prometheus.CounterOpts(opts))
}
func NewVecCounter(opts CounterOpts, labels []string) CounterVec {
return prometheus.NewCounterVec(prometheus.CounterOpts(opts), labels)
}
func NewGauge(opts GaugeOpts) Gauge {
return prometheus.NewGauge(prometheus.GaugeOpts(opts))
}
func NewHistogram(opts HistogramOpts) prometheus.Histogram {
return prometheus.NewHistogram(prometheus.HistogramOpts(opts))
}