Reviews Prometheus instrumentation in Go code for proper metric types, labels, and patterns. Use when reviewing code with prometheus/client_golang metrics.
| 测量项 | 类型 | 示例 |
|---|---|---|
| 处理的请求数 | 计数器 | requeststotal |
| 队列中的项目数 |
go
// 错误 - 每个用户/请求唯一
counter := promauto.NewCounterVec(
prometheus.CounterOpts{Name: requests_total},
[]string{user_id, path}, // 数百万个序列!
)
counter.WithLabelValues(userID, request.URL.Path).Inc()
// 正确 - 有界的标签值
counter := promauto.NewCounterVec(
prometheus.CounterOpts{Name: requests_total},
[]string{method, status_code}, // <100个序列
)
counter.WithLabelValues(r.Method, statusCode).Inc()
go
// 错误 - 对单调递增的值使用仪表盘
requestCount := promauto.NewGauge(prometheus.GaugeOpts{
Name: http_requests,
})
requestCount.Inc() // 应该使用计数器!
// 正确
requestCount := promauto.NewCounter(prometheus.CounterOpts{
Name: httprequeststotal,
})
requestCount.Inc()
go
// 错误 - 每次请求创建新指标
func handler(w http.ResponseWriter, r *http.Request) {
counter := prometheus.NewCounter(...) // 每次都创建新的!
prometheus.MustRegister(counter) // 重复时崩溃!
}
// 正确 - 只注册一次
var requestCounter = promauto.NewCounter(prometheus.CounterOpts{
Name: httprequeststotal,
})
func handler(w http.ResponseWriter, r *http.Request) {
requestCounter.Inc()
}
go
// 错误
duration := promauto.NewHistogram(prometheus.HistogramOpts{
Name: request_duration, // 没有单位!
})
// 正确
duration := promauto.NewHistogram(prometheus.HistogramOpts{
Name: requestdurationseconds, // 名称中包含单位
})
go
var (
httpRequests = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: myapp,
Subsystem: http,
Name: requests_total,
Help: 处理的HTTP请求总数,
},
[]string{method, status},
)
httpDuration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: myapp,
Subsystem: http,
Name: requestdurationseconds,
Help: HTTP请求延迟,
Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10},
},
[]string{method},
)
)
go
func metricsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer := prometheus.NewTimer(httpDuration.WithLabelValues(r.Method))
defer timer.ObserveDuration()
wrapped := &responseWriter{ResponseWriter: w, status: 200}
next.ServeHTTP(wrapped, r)
httpRequests.WithLabelValues(r.Method, strconv.Itoa(wrapped.status)).Inc()
})
}
go
import github.com/prometheus/client_golang/prometheus/promhttp
func main() {
http.Handle(/metrics, promhttp.Handler())
http.ListenAndServe(:9090, nil)
}
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 prometheus-go-code-review-1776089581 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 prometheus-go-code-review-1776089581 技能
skillhub install prometheus-go-code-review-1776089581
文件大小: 2.28 KB | 发布时间: 2026-4-14 09:40