首先引入Prometheus客户端库,然后定义并注册请求计数器和响应时间直方图等指标,接着通过promhttp暴露/metrics接口,再在中间件中记录请求数和耗时,最后配置Prometheus抓取目标实现监控。

在Go语言开发的微服务或Web应用中,集成Prometheus监控是实现可观测性的常见做法。通过暴露指标接口并交由Prometheus抓取,可以实时掌握服务的运行状态,比如请求量、响应时间、错误率等。下面介绍如何在Golang项目中快速接入Prometheus。
要在Go项目中使用Prometheus,需要引入官方提供的客户端库。该库支持定义和暴露各种类型的监控指标。
go get github.com/prometheus/client_golang/prometheus其中,prometheus 包用于定义指标,promhttp 提供了用于暴露指标的HTTP处理器。
常见的指标类型包括计数器(Counter)、仪表盘(Gauge)、直方图(Histogram)和摘要(Summary)。根据实际需求选择合适的类型。
立即学习“go语言免费学习笔记(深入)”;
例如,定义一个请求计数器和响应时间直方图:
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"method", "endpoint", "code"},
)
<pre class='brush:php;toolbar:false;'>httpResponseTime = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_response_time_seconds",
Help: "Histogram of response time for HTTP requests.",
Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0},
},
[]string{"method", "endpoint"},
))
注册这些指标到默认的注册中心:
func init() {
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(httpResponseTime)
}
使用 promhttp 将指标通过HTTP端点暴露出来,通常挂载在 /metrics 路径。
示例:使用标准 net/http 启动一个监控端口:
import (
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
<p>func startMetricsServer() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":9091", nil)
}</p>也可以将该Handler集成进现有服务,比如 Gin 或 Echo 框架中:
r := gin.New()
r.GET("/metrics", gin.WrapH(promhttp.Handler()))
在处理请求时记录相关数据。例如,在中间件中统计请求数和耗时:
func metricsMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
<pre class='brush:php;toolbar:false;'> next.ServeHTTP(w, r)
// 假设能获取状态码(需包装ResponseWriter)
httpRequestsTotal.WithLabelValues(
r.Method,
r.URL.Path,
"200", // 实际应动态获取
).Inc()
httpResponseTime.WithLabelValues(
r.Method,
r.URL.Path,
).Observe(time.Since(start).Seconds())
}}
注意:要准确获取状态码,建议封装 http.ResponseWriter 实现 WriteHeader 方法拦截。
配置Prometheus抓取目标时,只需在 prometheus.yml 中添加:
scrape_configs:
- job_name: 'my-go-service'
static_configs:
- targets: ['your-service-ip:9091']
启动Prometheus后,访问其Web界面即可看到采集到的指标。
基本上就这些。只要定义好关键指标,暴露/metrics接口,并让Prometheus定期抓取,就能完成基础监控接入。后续可结合Grafana做可视化展示,提升排查效率。
以上就是Golang如何使用Prometheus监控服务_Golang Prometheus监控操作指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号