监控用 Go 编写的 HTTP 服务器
在这篇教程中,我们将创建一个简单的 Go HTTP 服务器,并通过添加 Counter 指标来对服务器进行监控,以跟踪由服务器处理的请求总数。
我们有一个简单的 HTTP 服务器,具有/ping端点,返回pong响应。
package main
import ( "fmt" "net/http")
func ping(w http.ResponseWriter, req *http.Request){ fmt.Fprintf(w,"pong")}
func main() { http.HandleFunc("/ping",ping)
http.ListenAndServe(":8090", nil)}编译并运行服务器
go build server.go./server现在在浏览器中打开http://localhost:8090/ping,您应该能看到pong。

现在让我们向服务器添加一个指标,用于跟踪对/ping端点发出的请求次数。这里适合使用 Counter 指标类型,因为我们知道请求计数不会减少,只会增加。
创建一个 Prometheus Counter:
var pingCounter = prometheus.NewCounter( prometheus.CounterOpts{ Name: "ping_request_count", Help: "No of request handled by Ping handler", },)接下来更新ping处理程序以使用pingCounter.Inc()增加 Counter 的计数。
func ping(w http.ResponseWriter, req *http.Request) { pingCounter.Inc() fmt.Fprintf(w, "pong")}然后将 Counter 注册到默认注册表并暴露指标。
func main() { prometheus.MustRegister(pingCounter) http.HandleFunc("/ping", ping) http.Handle("/metrics", promhttp.Handler()) http.ListenAndServe(":8090", nil)}prometheus.MustRegister函数将pingCounter注册到默认注册表。
为了暴露指标,Go Prometheus 客户端库提供了promhttp 包。promhttp.Handler()提供了一个http.Handler,用于暴露在默认注册表中注册的指标。
完整示例代码:
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_examplego mod tidygo run server.go现在多次访问localhost:8090/ping。

在这里,ping_request_count显示/ping端点被调用 3 次。
默认注册表(Default Register)带有 Go 运行时指标的 Collector,这就是为什么我们看到诸如go_threads、go_goroutines等其他指标的原因。
现在,我们拉起了第一个指标 Exporter,让我们更新 Prometheus 配置从我们的服务器抓取指标。
global: scrape_interval: 15s
scrape_configs: - job_name: prometheus static_configs: - targets: ["localhost:9090"] - job_name: simple_server static_configs: - targets: ["localhost:8090"]执行prometheus --config.file=prometheus.yml启动 Prometheus 即可实现指标抓取。
该文档基于 Prometheus 官方文档翻译而成。