90 lines
2.5 KiB
Go
90 lines
2.5 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
"github.com/prometheus/client_golang/prometheus/push"
|
|
"qoobing.com/gomod/log"
|
|
)
|
|
|
|
var (
|
|
MetricExporterPusher = func() error { return nil }
|
|
MetricExporterHandler Handler = nil
|
|
metricRegistry *prometheus.Registry = nil
|
|
metricApiCounter *prometheus.CounterVec = nil
|
|
metricApiSummary *prometheus.SummaryVec = nil
|
|
)
|
|
|
|
type metricExporterHandler struct {
|
|
name string
|
|
promhttpHandler http.Handler
|
|
}
|
|
|
|
func (m *metricExporterHandler) ApiName() string {
|
|
return m.name
|
|
}
|
|
|
|
func (m *metricExporterHandler) HandlerFunc() HandlerFunc {
|
|
return func(c *Context) (err error) {
|
|
m.promhttpHandler.ServeHTTP(c.Writer, c.Request)
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func dumpMetricExporterPusher() error {
|
|
return errors.New("not initilized, forgot call 'SetupMetricsExporterPusher'?")
|
|
}
|
|
|
|
func InitMetrics() {
|
|
instance := getInstanceIpAddress()
|
|
log.Infof("self instance ip: [%s]", instance)
|
|
metricApiCounter = prometheus.NewCounterVec(
|
|
prometheus.CounterOpts{
|
|
Name: "api_requests_total",
|
|
Help: "How many HTTP requests processed",
|
|
ConstLabels: prometheus.Labels{"instance": instance},
|
|
},
|
|
[]string{"api", "errcode", "appid"},
|
|
)
|
|
metricApiSummary = prometheus.NewSummaryVec(
|
|
prometheus.SummaryOpts{
|
|
Name: "api_requests_summary",
|
|
Help: "The api request summary of cost.",
|
|
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
|
|
ConstLabels: prometheus.Labels{"instance": instance},
|
|
},
|
|
[]string{"api", "errcode", "appid"},
|
|
)
|
|
metricRegistry = prometheus.NewRegistry()
|
|
metricRegistry.MustRegister(metricApiCounter)
|
|
metricRegistry.MustRegister(metricApiSummary)
|
|
}
|
|
|
|
func SetupMetricsExporterHandler(apiname string) {
|
|
if apiname == "" {
|
|
apiname = "premetheus_metrics_exporter"
|
|
}
|
|
|
|
opt := promhttp.HandlerOpts{Registry: metricRegistry}
|
|
MetricExporterHandler = &metricExporterHandler{
|
|
name: apiname,
|
|
promhttpHandler: promhttp.HandlerFor(metricRegistry, opt),
|
|
}
|
|
}
|
|
|
|
func SetupMetricsExporterPusher(pushgateway string, jobname string) {
|
|
if jobname == "" {
|
|
jobname = fmt.Sprintf("api-metrics-job-%s", getExeFilename())
|
|
}
|
|
|
|
var pusher = push.New(pushgateway, jobname).Gatherer(metricRegistry)
|
|
MetricExporterPusher = func() error {
|
|
RecordMetrics("push_metrics_to_prometheus", "0", "selfmonitoring", 1.0)
|
|
return pusher.Push()
|
|
}
|
|
}
|