Golang Prometheus监控集成教程
在Golang项目中集成Prometheus监控时,如何正确配置和暴露metrics端点?我按照官方文档添加了Prometheus客户端库,但访问/metrics时总是返回404错误。具体应该在哪里初始化HTTP handler?自定义的指标(比如请求计数器)是否需要额外注册?另外,在生产环境中部署时,Prometheus的scrape_config应该如何配置才能自动发现Golang服务的metrics端点?
首先,在项目中引入Prometheus客户端库:
go get github.com/prometheus/client_golang/prometheus
然后创建自定义指标,比如计数器、摘要等:
package main
import (
"github.com/prometheus/client_golang/prometheus"
)
var exampleCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "example_counter",
Help: "Example counter metric",
})
var exampleSummary = prometheus.NewSummary(prometheus.SummaryOpts{
Name: "example_summary",
Help: "Example summary metric",
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
})
接着在初始化时注册这些指标:
prometheus.MustRegister(exampleCounter)
prometheus.MustRegister(exampleSummary)
在业务逻辑中更新指标值,例如计数器自增:
exampleCounter.Inc()
运行HTTP服务以暴露指标数据:
http.Handle("/metrics", prometheus.Handler())
最后启动HTTP服务器监听请求:
http.ListenAndServe(":8080", nil)
这样,Prometheus就能抓取到你的自定义指标了。记得配置Prometheus任务去拉取这个地址的数据。
更多关于Golang Prometheus监控集成教程的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
集成Prometheus监控到Golang应用非常简单。首先,在项目中引入github.com/prometheus/client_golang/prometheus
和github.com/prometheus/client_golang/prometheus/promhttp
两个库。
- 初始化指标:
package main
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var myCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "my_counter",
Help: "Incremented on every request.",
},
[]string{"handler"},
)
- 注册指标:
func init() {
prometheus.MustRegister(myCounter)
}
- 在处理请求时增加计数:
func handleRequest(w http.ResponseWriter, r *http.Request) {
myCounter.WithLabelValues("example").Inc()
w.Write([]byte("Hello, Prometheus!"))
}
- 暴露监控端点:
func main() {
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
}
这样,Prometheus就可以抓取/metrics
接口的数据了。记得配置Prometheus的配置文件,添加目标地址job: "go_app"
和对应的URL。