Go服务集成Prometheus监控需暴露/metrics端点,用官方客户端注册Counter、Gauge、Histogram等指标,中间件统一埋点记录请求量与耗时,Prometheus通过配置static_configs抓取数据。

在 Go 服务中集成 Prometheus 监控,核心是暴露符合 Prometheus 格式的指标端点,并用官方客户端库自动注册和更新指标。不需要手动拼接文本格式,也不需要自己实现 HTTP handler —— promhttp 和 prometheus 客户端已封装好标准流程。
使用官方库 github.com/prometheus/client_golang/prometheus 注册常用指标类型(Counter、Gauge、Histogram、Summary):
示例:注册一个请求计数器和响应延迟直方图
goimport (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
<p>var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "status_code"},
)
httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration in seconds",
Buckets: prometheus.DefBuckets, // 或自定义 [0.01, 0.025, 0.05, ...]
},
[]string{"method", "path"},
)
)</p><p>func init() {
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(httpRequestDuration)
}在实际 handler 中调用 Inc()、Observe() 等方法更新指标值。建议配合中间件统一埋点,避免每个 handler 重复写:
立即学习“go语言免费学习笔记(深入)”;
httpRequestsTotal.WithLabelValues(r.Method, strconv.Itoa(status)).Inc() 记录一次请求httpRequestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(latency.Seconds()) 记录耗时只需一行代码挂载标准 handler:
gohttp.Handle("/metrics", promhttp.Handler())启动服务后访问 http://localhost:8080/metrics 即可看到纯文本格式指标(如 http_requests_total{method="GET",status_code="200"} 42)。Prometheus server 抓取该地址即可采集数据。
在 Prometheus 的 prometheus.yml 中添加 job:
scrape_configs:
- job_name: 'my-go-service'
static_configs:
- targets: ['localhost:8080']重启 Prometheus 后,在 Web UI 的 Status > Targets 页面确认目标为 UP 状态,再通过 Graph 查询如 rate(http_requests_total[5m]) 验证数据是否正常上报。
基本上就这些。不复杂但容易忽略的是 label 设计和 Histogram 的 bucket 设置 —— 这两点直接影响监控可用性和资源开销。
以上就是如何在Golang中实现服务监控_使用Prometheus采集服务指标的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号