代码解释
- 创建Prometheus counter
var pingCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "ping_request_count",
Help: "No of request handled by Ping handler",
},
)
- 我们使用 pingCounter.Inc() 更新 ping 处理程序以增加计数器的计数
func ping(w http.ResponseWriter, req *http.Request) {
pingCounter.Inc()
fmt.Fprintf(w, "pong")
}
- 然后将计数器注册到默认寄存器并公开指标
func main() {
prometheus.MustRegister(pingCounter)
http.HandleFunc("/ping", ping)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8090", nil)
}
prometheus.MustRegister 函数将 pingCounter 注册到默认的 Register 中。为了公开指标,Go Prometheus 客户端库提供了 promhttp 包。 promhttp.Handler() 提供了一个 http.Handler,它公开了在默认寄存器中注册的指标。
注: 注册后的指标是有默认的其他指标的,如果不想要这些的话,可以通过prometheus.NewRegistry()来生成新注册器
func main() {
registry := prometheus.NewRegistry()
registry.MustRegister(pingCounter)
http.HandleFunc("/ping", ping)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8090", nil)
}
最终程序
package main
import (
"fmt"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var pingCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "ping_request_count",
Help: "No of request handled by Ping handler",
},
)
func ping(w http.ResponseWriter, req *http.Request) {
pingCounter.Inc()
fmt.Fprintf(w, "pong")
}
func main() {
prometheus.MustRegister(pingCounter)
http.HandleFunc("/ping", ping)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8090", nil)
}
运行程序
go mod init prom_example
go mod tidy
go run server.go
测试
现在点击 localhost:8090/ping 端点几次并向 localhost:8090 发送请求更新指标counter。