Loading

Gin接入Prometheus

这里监控了一个访问端点/ping次数

package main

import (
	"regexp"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var pingCounter = prometheus.NewCounter(
	prometheus.CounterOpts{
		Name: "ping_request_count",
		Help: "No of request handled by Ping handler",
	},
)

func pingHandler(c *gin.Context) {
	pingCounter.Inc()
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

func register() prometheus.Gatherer {
	reg := prometheus.NewRegistry()
	reg.MustRegister(pingCounter)
	reg.MustRegister(collectors.NewBuildInfoCollector())
	reg.MustRegister(collectors.NewGoCollector(
		collectors.WithGoCollectorRuntimeMetrics(collectors.GoRuntimeMetricsRule{Matcher: regexp.MustCompile("/.*")}),
	))
	return reg
}
func main() {
	r := gin.Default()
	reg := register()
	r.GET("/metrics", gin.WrapH(promhttp.HandlerFor(
		reg,
		promhttp.HandlerOpts{
			EnableOpenMetrics: true,
		})))
	r.GET("/ping", pingHandler)
	r.Run(":8090")
}


posted @ 2022-11-03 10:32  头痛不头痛  阅读(619)  评论(0编辑  收藏  举报