在本教程中,我们将创建一个简单的 Go HTTP 服务器,并通过添加一个计数器指标来对其进行检测,以记录服务器处理的总请求数。

这里有一个简单的 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

Server

现在让我们向服务器添加一个指标,它将记录对 ping 端点发出的请求数。计数器指标类型适用于此,因为我们知道请求计数不会减少,只会增加。

创建一个 Prometheus 计数器

var pingCounter = prometheus.NewCounter(
   prometheus.CounterOpts{
       Name: "ping_request_count",
       Help: "No of request handled by Ping handler",
   },
)

接下来,让我们更新 ping Handler,使用 pingCounter.Inc() 增加计数器的值。

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 注册到默认注册器。为了暴露指标,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_example
go mod tidy
go run server.go

现在多次访问 localhost:8090/ping 端点,然后向 localhost:8090 发送请求即可获取指标。

Ping Metric

这里 ping_request_count 显示 /ping 端点被调用了 3 次。

默认注册器包含一个用于 Go 运行时指标的收集器,这就是为什么我们会看到其他指标,例如 go_threadsgo_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

本文档是开源的。请通过提交问题或拉取请求帮助改进它。