Prometheus监控go服务端
在本教程中,我们将创建一个简单的Go语言编写的HTTP服务器,并通过添加一个计数器指标来监控服务器处理的总请求数。
这里我们有一个简单的HTTP服务器,它有一个
/ping
端点,返回
pong
作为响应。
1 | ``` |
go build server.go
./server
1 |
|
var pingCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Name: “ping_request_count”,
Help: “由Ping处理器处理的请求数量”,
},
)
1 |
|
func ping(w http.ResponseWriter, req *http.Request) {
pingCounter.Inc()
fmt.Fprintf(w, “pong”)
}
1 |
|
func main() {
prometheus.MustRegister(pingCounter)
http.HandleFunc(“/ping”, ping)
http.Handle(“/metrics”, promhttp.Handler())
http.ListenAndServe(“:8090”, nil)
}
1 |
|
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 |
|
go mod init prom_example
go mod tidy
go run server.go
1 |
|
global:
scrape_interval: 15s
scrape_configs:
- job_name: prometheus
static_configs:- targets: [“localhost:9090”]
- job_name: simple_server
static_configs:- targets: [“localhost:8090”]
1 |
|
prometheus --config.file=prometheus.yml
