golang-lib/web/metrics/main.go

68 lines
1.4 KiB
Go
Raw Permalink Normal View History

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-06-01 10:51:35 +02:00
// db metrics
gormPrometheus "gorm.io/plugin/prometheus"
2023-10-23 21:40:10 +02:00
"codeberg.org/genofire/golang-lib/web"
2021-06-01 10:51:35 +02:00
)
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
}
)
// 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
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
if ws.DB != nil {
ws.DB.Use(gormPrometheus.New(gormPrometheus.Config{
DBName: NAMESPACE,
RefreshInterval: 15,
}))
2021-06-01 10:51:35 +02:00
}
2021-06-01 10:51:35 +02:00
r.GET("/metrics", ginprom.PromHandler(promhttp.Handler()))
2021-06-01 10:51:35 +02:00
}