1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
| import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
// Counter:只增不减的计数器
requestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "endpoint", "status"},
)
// Histogram:分布统计(延迟、请求大小)
requestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request latency distributions",
Buckets: []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
},
[]string{"method", "endpoint"},
)
// Gauge:可增可减的数值(当前连接数、队列长度)
activeConnections = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "http_active_connections",
Help: "Current number of active connections",
},
)
// Summary:类似 Histogram,但客户端计算分位数
responseSize = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "http_response_size_bytes",
Help: "HTTP response size distributions",
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
},
[]string{"method", "endpoint"},
)
)
func init() {
// 注册指标
prometheus.MustRegister(requestsTotal)
prometheus.MustRegister(requestDuration)
prometheus.MustRegister(activeConnections)
prometheus.MustRegister(responseSize)
}
// HTTP 中间件
func PrometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// 包装 ResponseWriter 以获取状态码
rw := &responseWriter{ResponseWriter: w, statusCode: 200}
// 处理请求
next.ServeHTTP(rw, r)
// 记录指标
duration := time.Since(start).Seconds()
requestsTotal.WithLabelValues(r.Method, r.URL.Path, strconv.Itoa(rw.statusCode)).Inc()
requestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(duration)
})
}
// 业务指标示例
type OrderService struct {
ordersCreated prometheus.Counter
orderAmount prometheus.Histogram
}
func (s *OrderService) CreateOrder(order *Order) error {
start := time.Now()
// 业务逻辑
if err := s.repo.Create(order); err != nil {
return err
}
// 记录业务指标
s.ordersCreated.Inc()
s.orderAmount.Observe(order.Amount)
// 记录处理时间
duration := time.Since(start).Seconds()
orderProcessingDuration.Observe(duration)
return nil
}
|