Middleware Prometheus 中间件
()
| 125 | |
| 126 | // Middleware Prometheus 中间件 |
| 127 | func (m *MetricsManager) Middleware() gin.HandlerFunc { |
| 128 | return func(c *gin.Context) { |
| 129 | start := time.Now() |
| 130 | path := c.FullPath() |
| 131 | if path == "" { |
| 132 | path = c.Request.URL.Path |
| 133 | } |
| 134 | |
| 135 | // 记录请求大小 |
| 136 | reqSize := computeRequestSize(c) |
| 137 | m.requestSize.WithLabelValues(c.Request.Method, path).Observe(float64(reqSize)) |
| 138 | |
| 139 | // 处理请求 |
| 140 | c.Next() |
| 141 | |
| 142 | // 记录指标 |
| 143 | duration := time.Since(start).Seconds() |
| 144 | status := c.Writer.Status() |
| 145 | |
| 146 | m.requestsTotal.WithLabelValues( |
| 147 | c.Request.Method, |
| 148 | path, |
| 149 | statusClass(status), |
| 150 | ).Inc() |
| 151 | |
| 152 | m.requestDuration.WithLabelValues( |
| 153 | c.Request.Method, |
| 154 | path, |
| 155 | ).Observe(duration) |
| 156 | |
| 157 | // 记录响应大小 |
| 158 | respSize := c.Writer.Size() |
| 159 | if respSize > 0 { |
| 160 | m.responseSize.WithLabelValues(c.Request.Method, path).Observe(float64(respSize)) |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // Handler Prometheus 指标暴露端点 |
| 166 | func (m *MetricsManager) Handler() gin.HandlerFunc { |
nothing calls this directly
no test coverage detected