api/prometheus.go
2023-03-06 11:55:47 +08:00

103 lines
2.8 KiB
Go

package api
import (
"errors"
"fmt"
"net/http"
"strings"
"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
instance string = "--unknown--"
)
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(instanceValue string) {
if instanceValue == "" {
instance = getInstanceIpAddress()
} else if ap := strings.Split(instanceValue, ":"); len(ap) == 2 &&
ap[0] == "0.0.0.0" || ap[0] == "" {
instance = getInstanceIpAddress() + ":" + ap[1]
}
log.Infof("self instance: [%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).
Grouping("instance", instance).
Gatherer(metricRegistry)
MetricExporterPusher = func() error {
RecordMetrics("push_metrics_to_prometheus", "0", "selfmonitoring", 1.0)
return pusher.Push()
}
}