prometheus/client_golang Go 库:完整指南
1. 什么是 prometheus/client_golang 以及为什么需要它
prometheus/client_golang 库是 Prometheus 监控系统的官方 Go 语言客户端。它为开发者提供了强大而灵活的工具,用于从 Go 应用程序中收集、聚合和导出指标。Prometheus 本身是 DevOps 和云计算领域(尤其是 Kubernetes 生态系统)中最流行的指标收集和监控系统之一。
为什么需要它?在现代微服务架构中,了解应用程序的运行状况至关重要:处理了多少请求、响应延迟如何、消耗了多少内存、错误发生的频率等。prometheus/client_golang 让你能够轻松地为代码添加这些指标。该库会自动提供一个端点(通常是 /metrics),Prometheus 可以按计划对其进行“抓取”(轮询)。这使你能够在 Grafana 中构建仪表板、配置警报,并全面了解服务的健康状况。
该库的关键功能包括支持 Prometheus 的四种主要指标类型:Counter(只增不减的计数器)、Gauge(可增可减的测量器)、Histogram(用于测量值分布,如响应时间的直方图)和 Summary(与直方图类似,但在客户端计算分位数)。此外,该库还提供了用于收集 Go 标准指标(内存、协程、GC)和 HTTP 服务器指标的便捷“收集器”。
2. 安装
使用标准的 go get 命令即可安装该库。请确保你已安装 Go 1.16 或更高版本(建议使用最新的稳定版本)。
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
执行这些命令后,你的 go.mod 文件中将出现相应的依赖项。prometheus 包包含库的核心功能(指标类型、注册),而 promhttp 则提供了用于导出指标的 HTTP 处理器。
3. 快速入门——最小工作示例
让我们创建一个最小应用程序,用于导出一个指标——已处理的 HTTP 请求数量。
package main
import (
"fmt"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
// 定义一个带有 "path" 标签的请求计数器
requestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"path"},
)
)
func init() {
// 在全局注册表中注册指标
prometheus.MustRegister(requestsTotal)
}
func main() {
// 主路径的处理器
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// 为路径 "/" 增加计数器
requestsTotal.WithLabelValues("/").Inc()
fmt.Fprintf(w, "Hello, World!")
})
// Prometheus 指标端点的处理器
http.Handle("/metrics", promhttp.Handler())
fmt.Println("Server started on :8080")
http.ListenAndServe(":8080", nil)
}
运行此代码(go run main.go),在浏览器中打开 http://localhost:8080/metrics。你将看到许多指标,包括我们的 http_requests_total。每次你访问 http://localhost:8080/ 时,该计数器的值都会增加。