2 Star 0 Fork 0

hero/momo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
prometheus_middle.go 1.34 KB
一键复制 编辑 原始数据 按行查看 历史
hero 提交于 2024-11-04 11:45 . upd:目录结构调整
package middle
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// 全局 Prometheus 指标
var (
CustomerRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "custom_http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"path", "method", "status"},
)
ThrottleCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "throttle_counter_total",
Help: "Total number of requests that passed the throttle.",
},
[]string{"resource", "status"},
)
)
func init() {
// 注册全局 Prometheus 指标
prometheus.MustRegister(CustomerRequestsTotal)
prometheus.MustRegister(ThrottleCounter)
}
// PrometheusMiddleware 记录常规的 HTTP 请求统计数据
func PrometheusMiddle() gin.HandlerFunc {
return func(c *gin.Context) {
// 记录请求总数
status := c.Writer.Status()
CustomerRequestsTotal.WithLabelValues(c.FullPath(), c.Request.Method, fmt.Sprintf("%d", status)).Inc()
// 处理请求
c.Next()
}
}
// 在 Gin 路由中注册 Prometheus 处理程序
func RegisterPrometheus(port int) {
http.Handle("/metrics", promhttp.Handler())
go func() {
fmt.Printf(" - using prometheus: %v\n", port)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}()
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/linqwen/momo.git
git@gitee.com:linqwen/momo.git
linqwen
momo
momo
v1.1.16

搜索帮助