Prometheus 指标在 Go (Golang) 中:完整指南
Prometheus 是一个强大的开源监控和告警系统,已成为云应用领域的事实标准。对于 Go (Golang) 语言,有一个官方客户端 prometheus/client_golang,可以轻松地将指标添加到您的应用程序中。在本文中,我们将详细介绍如何安装该库、创建主要指标类型(counter、gauge、histogram)以及通过 HTTP 导出它们。
1. 安装库
要在 Go 中使用 Prometheus,需要安装 prometheus/client_golang 包。执行以下命令:
go get github.com/prometheus/client_golang/prometheusgo get github.com/prometheus/client_golang/prometheus/promhttp第一个包包含主要的指标类型,第二个包包含用于以 Prometheus 服务器可理解的格式导出指标的 HTTP 处理器。
2. 主要指标类型
Prometheus 支持四种主要指标类型。我们来介绍三种最流行的:
- Counter — 只增不减的计数器(例如,请求数量)。
- Gauge — 可增可减的值(例如,活跃连接数)。
- Histogram — 测量值分布情况的直方图(例如,响应时间)。
3. 示例:Counter(请求计数器)
让我们创建一个简单的 HTTP 服务器,用于统计已处理的请求数量:
package main
import ( "fmt" "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp")
var ( requestsTotal = prometheus.NewCounter( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests.", }, ))
func init() { prometheus.MustRegister(requestsTotal)}
func handler(w http.ResponseWriter, r *http.Request) { requestsTotal.Inc() fmt.Fprintf(w, "Hello, you are visitor #%d", requestsTotal)}
func main() { http.HandleFunc("/", handler) http.Handle("/metrics", promhttp.Handler()) http.ListenAndServe(":8080", nil)}在这个示例中:
prometheus.NewCounter创建一个名为http_requests_total的计数器。prometheus.MustRegister将指标注册到全局注册表中。requestsTotal.Inc()每次请求时将计数器增加 1。promhttp.Handler()在/metrics地址导出所有已注册的指标。
4. 示例:Gauge(活跃连接数)
Gauge 非常适合跟踪当前状态,例如活跃的 goroutine 数量:
var ( activeGoroutines = prometheus.NewGauge( prometheus.GaugeOpts{ Name: "active_goroutines", Help: "Current number of active goroutines.", }, ))
func monitorGoroutines() { for { activeGoroutines.Set(float64(runtime.NumGoroutine())) time.Sleep(5 * time.Second) }}
func main() { prometheus.MustRegister(activeGoroutines) go monitorGoroutines() // ... 其余代码}这里 Set() 设置当前值,而 Inc() 和 Dec() 允许将 gauge 增加或减少 1。
5. 示例:Histogram(响应时间)
Histogram 收集观测值并将其分布到可配置的桶(buckets)中:
var ( requestDuration = prometheus.NewHistogram( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "Histogr