package api import ( "fmt" "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/push" ) var ( MetricExporterPusher = func() {} 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 InitMetrics() { metricApiCounter = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "api_requests_total", Help: "How many HTTP requests processed", }, []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}, }, []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() { pusher.Push() } }