Prometheus监控go服务端

在本教程中,我们将创建一个简单的Go语言编写的HTTP服务器,并通过添加一个计数器指标来监控服务器处理的总请求数。

这里我们有一个简单的HTTP服务器,它有一个
/ping端点,返回
pong作为响应。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
```
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  
```

现在打开浏览器访问
`http://localhost:8090/ping`,你应该能看到
`pong`。

![](/images/blog/1742927618693_image_1.png)

现在让我们为服务器添加一个指标,用于监控对
`ping`端点的请求次数,计数器指标类型适合这个用途,因为我们知道请求次数不会减少,只会增加。

创建一个Prometheus计数器

```go

var pingCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Name: “ping_request_count”,
Help: “由Ping处理器处理的请求数量”,
},
)

1
2
3
4
5
6
7
8
  
```

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

```go

func ping(w http.ResponseWriter, req *http.Request) {
pingCounter.Inc()
fmt.Fprintf(w, “pong”)
}

1
2
3
4
5
6
  
```

然后,将计数器注册到默认注册表,并暴露指标。

```go

func main() {
prometheus.MustRegister(pingCounter)
http.HandleFunc(“/ping”, ping)
http.Handle(“/metrics”, promhttp.Handler())
http.ListenAndServe(“:8090”, nil)
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  
```

`prometheus.MustRegister`函数将
`pingCounter`注册到默认注册表。

为了暴露指标,Go Prometheus客户端库提供了
`promhttp`包。

`promhttp.Handler()`提供了一个
`http.Handler`,它暴露了在默认注册表中注册的指标。

示例代码依赖于

```go

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: “由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)
}

1
2
3
4
5
6
  
```

运行示例

```

go mod init prom_example
go mod tidy
go run server.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  
```

现在多次访问
`localhost:8090/ping`端点,并向
`localhost:8090`发送请求将提供指标。

![](/images/blog/1742927618693_image_2.png)

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

默认注册表附带了一个收集Go运行时指标的收集器,这就是为什么我们可以看到其他指标,如
`go_threads`、
`go_goroutines`等。

我们已经构建了我们的第一个指标导出器。让我们更新我们的Prometheus配置,从我们的服务器抓取指标。

```

global:
scrape_interval: 15s
scrape_configs:

  • job_name: prometheus
    static_configs:
    • targets: [“localhost:9090”]
  • job_name: simple_server
    static_configs:
    • targets: [“localhost:8090”]
1
2
  
```

prometheus --config.file=prometheus.yml

  
  



![江达小记](/images/wechatmpscan.png)