2021-06-01 10:51:35 +02:00
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
|
|
// gin-prometheus
|
|
|
|
"github.com/chenjiandongx/ginprom"
|
|
|
|
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2021-07-19 17:59:08 +02:00
|
|
|
|
2021-06-01 10:51:35 +02:00
|
|
|
// db metrics
|
|
|
|
gormPrometheus "gorm.io/plugin/prometheus"
|
|
|
|
|
|
|
|
"dev.sum7.eu/genofire/golang-lib/web"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2021-06-01 17:41:05 +02:00
|
|
|
// NAMESPACE of prometheus metrics
|
|
|
|
NAMESPACE string = "service"
|
|
|
|
// VERSION in prometheus metrics
|
|
|
|
VERSION string = ""
|
|
|
|
// UP function for healthy check in prometheus metrics
|
|
|
|
UP func() bool = func() bool {
|
2021-06-01 10:51:35 +02:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2021-07-19 17:59:08 +02:00
|
|
|
// Register to WebService
|
|
|
|
func Register(r *gin.Engine, ws *web.Service) {
|
|
|
|
r.Use(ginprom.PromMiddleware(&ginprom.PromOpts{
|
|
|
|
EndpointLabelMappingFn: func(c *gin.Context) string {
|
|
|
|
url := c.Request.URL.Path
|
|
|
|
for _, p := range c.Params {
|
|
|
|
url = strings.Replace(url, p.Value, ":"+p.Key, 1)
|
|
|
|
}
|
|
|
|
return url
|
|
|
|
},
|
|
|
|
}))
|
2021-06-01 10:51:35 +02:00
|
|
|
|
2021-07-19 17:59:08 +02:00
|
|
|
prometheus.MustRegister(prometheus.NewGaugeFunc(
|
|
|
|
prometheus.GaugeOpts{
|
|
|
|
Namespace: NAMESPACE,
|
|
|
|
Name: "up",
|
|
|
|
Help: "is current version of service running",
|
|
|
|
ConstLabels: prometheus.Labels{"version": VERSION},
|
|
|
|
},
|
|
|
|
func() float64 {
|
|
|
|
if UP() {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
return 0
|
|
|
|
},
|
|
|
|
))
|
2021-06-01 10:51:35 +02:00
|
|
|
|
2021-07-19 17:59:08 +02:00
|
|
|
if ws.DB != nil {
|
|
|
|
ws.DB.Use(gormPrometheus.New(gormPrometheus.Config{
|
|
|
|
DBName: NAMESPACE,
|
|
|
|
RefreshInterval: 15,
|
|
|
|
}))
|
2021-06-01 10:51:35 +02:00
|
|
|
|
2021-07-19 17:59:08 +02:00
|
|
|
}
|
2021-06-01 10:51:35 +02:00
|
|
|
|
2021-07-19 17:59:08 +02:00
|
|
|
r.GET("/metrics", ginprom.PromHandler(promhttp.Handler()))
|
2021-06-01 10:51:35 +02:00
|
|
|
}
|