Prometheus 拥有一个官方的 Go 客户端库,你可以使用它对 Go 应用程序进行插桩。在本指南中,我们将创建一个简单的 Go 应用程序,通过 HTTP 暴露 Prometheus 指标。
NOTE: 如需全面的 API 文档,请参阅 Prometheus 各种 Go 库的 GoDoc。
安装
你可以使用 go get 安装本指南所需的 prometheus、promauto 和 promhttp 库:
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promauto
go get github.com/prometheus/client_golang/prometheus/promhttp
Go 暴露指标的工作原理
要在 Go 应用程序中暴露 Prometheus 指标,你需要提供一个 /metrics HTTP 端点。你可以使用 prometheus/promhttp 库的 HTTP Handler 作为处理函数。
例如,以下最小应用程序将通过 http://localhost:2112/metrics 暴露 Go 应用程序的默认指标:
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
reg := prometheus.NewRegistry()
reg.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
http.ListenAndServe(":2112", nil)
}
启动应用程序:
go run main.go
访问指标:
curl http://localhost:2112/metrics
添加自定义指标
上面的应用程序只暴露了默认的 Go 指标。你也可以注册自己的自定义应用程序特定指标。此示例应用程序暴露了一个 myapp_processed_ops_total 计数器,用于计算到目前为止已处理的操作数量。每 2 秒,计数器增加 1。
package main
import (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type metrics struct {
opsProcessed prometheus.Counter
}
func newMetrics(reg prometheus.Registerer) *metrics {
m := &metrics{
opsProcessed: promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "myapp_processed_ops_total",
Help: "The total number of processed events",
}),
}
return m
}
func recordMetrics(m *metrics) {
go func() {
for {
m.opsProcessed.Inc()
time.Sleep(2 * time.Second)
}
}()
}
func main() {
reg := prometheus.NewRegistry()
m := newMetrics(reg)
recordMetrics(m)
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
http.ListenAndServe(":2112", nil)
}
运行应用程序:
go run main.go
访问指标:
curl http://localhost:2112/metrics
在指标输出中,你将看到 myapp_processed_ops_total 计数器的帮助文本、类型信息和当前值:
# HELP myapp_processed_ops_total The total number of processed events
# TYPE myapp_processed_ops_total counter
myapp_processed_ops_total 5
你可以配置本地运行的 Prometheus 实例来抓取该应用程序的指标。以下是一个示例 prometheus.yml 配置:
scrape_configs:
- job_name: myapp
scrape_interval: 10s
static_configs:
- targets:
- localhost:2112
其他 Go 客户端功能
在本指南中,我们仅介绍了 Prometheus Go 客户端库中一小部分可用功能。你还可以暴露其他指标类型,如 gauge 和 histogram、非全局注册表、将指标推送到 Prometheus PushGateway 的函数、桥接 Prometheus 和 Graphite 等功能。
总结
在本指南中,你创建了两个示例 Go 应用程序来向 Prometheus 暴露指标---一个仅暴露默认 Go 指标,另一个还暴露了一个自定义 Prometheus 计数器---并配置了一个 Prometheus 实例来抓取这些应用程序的指标。