package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
"time"
)
var (
WebRequestTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "web_reqeust_total",
Help: "Number of hello requests in total",
}, []string{"method", "path"})
WebRequestDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Histogram of the duration of HTTP requests",
Buckets: prometheus.DefBuckets,
}, []string{"method", "path"})
)
func init() {
// 注册计数器到 Prometheus
prometheus.MustRegister(WebRequestTotal)
// 注册直方图到 Prometheus
prometheus.MustRegister(WebRequestDurationHistogram)
}
func main() {
r := gin.Default() //创建gin
r.Use(func(c *gin.Context) {
start := time.Now()
//处理请求
c.Next()
duration := time.Since(start).Seconds()
//记录请求次数
WebRequestTotal.WithLabelValues(c.Request.Method, c.Request.URL.Path).Inc()
//记录http方法和路径对应的耗时
WebRequestDurationHistogram.WithLabelValues(c.Request.Method, c.Request.URL.Path).Observe(duration)
})
r.GET("/", index) //绑定路由
r.GET("/metrics", gin.WrapH(promhttp.Handler()))
r.Run(":8001") //运行绑定端口
}
func index(c *gin.Context) {
fmt.Println("1111")
c.JSON(200, gin.H{
"message": "how are you?怎么是你?",
})
}
标签:收集,Request,prometheus,Prometheus,func,duration,gin
From: https://www.cnblogs.com/qcy-blog/p/18360985