Files
open-im-server/pkg/common/prome/prometheus.go
T

83 lines
1.6 KiB
Go
Raw Normal View History

2023-02-15 15:52:32 +08:00
package prome
2022-09-12 19:32:24 +08:00
import (
2023-02-23 19:15:30 +08:00
"OpenIM/pkg/common/config"
2022-09-15 01:22:20 +08:00
"bytes"
2022-09-12 19:32:24 +08:00
"net/http"
"strconv"
"github.com/gin-gonic/gin"
2022-09-14 17:45:38 +08:00
"github.com/prometheus/client_golang/prometheus"
2022-09-12 19:32:24 +08:00
"github.com/prometheus/client_golang/prometheus/promhttp"
)
2023-02-24 11:13:16 +08:00
func StartPrometheusSrv(prometheusPort int) error {
2022-09-12 19:32:24 +08:00
if config.Config.Prometheus.Enable {
http.Handle("/metrics", promhttp.Handler())
2023-02-22 19:51:14 +08:00
err := http.ListenAndServe(":"+strconv.Itoa(prometheusPort), nil)
2022-09-12 19:32:24 +08:00
return err
}
return nil
}
func PrometheusHandler() gin.HandlerFunc {
h := promhttp.Handler()
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
}
2022-09-14 17:45:38 +08:00
2022-09-15 01:22:20 +08:00
type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (r responseBodyWriter) Write(b []byte) (int, error) {
r.body.Write(b)
return r.ResponseWriter.Write(b)
}
2023-02-24 11:13:16 +08:00
func PrometheusMiddleware(c *gin.Context) {
Inc(ApiRequestCounter)
2022-09-15 01:22:20 +08:00
w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
c.Writer = w
c.Next()
if c.Writer.Status() == http.StatusOK {
2023-02-24 11:13:16 +08:00
Inc(ApiRequestSuccessCounter)
2022-09-15 01:22:20 +08:00
} else {
2023-02-24 11:13:16 +08:00
Inc(ApiRequestFailedCounter)
2022-09-15 01:22:20 +08:00
}
}
2023-02-24 11:13:16 +08:00
func Inc(counter prometheus.Counter) {
2022-09-14 17:45:38 +08:00
if config.Config.Prometheus.Enable {
2022-09-14 21:42:04 +08:00
if counter != nil {
counter.Inc()
}
2022-09-14 17:45:38 +08:00
}
}
2022-09-14 19:28:17 +08:00
2023-02-24 11:13:16 +08:00
func Add(counter prometheus.Counter, add int) {
2022-09-14 19:28:17 +08:00
if config.Config.Prometheus.Enable {
2022-09-14 21:42:04 +08:00
if counter != nil {
counter.Add(float64(add))
}
2022-09-14 19:28:17 +08:00
}
}
2022-09-15 17:50:45 +08:00
2023-02-24 11:13:16 +08:00
func GaugeInc(gauges prometheus.Gauge) {
2022-09-15 17:50:45 +08:00
if config.Config.Prometheus.Enable {
if gauges != nil {
gauges.Inc()
}
}
}
2023-02-24 11:13:16 +08:00
func GaugeDec(gauges prometheus.Gauge) {
2022-09-15 17:50:45 +08:00
if config.Config.Prometheus.Enable {
if gauges != nil {
gauges.Dec()
}
}
}