Go应用集成Prometheus监控需暴露/metrics端点并注册指标,Prometheus拉取数据,告警由Alertmanager处理;自定义指标须早期注册,配置需确保路径、目标和规则一致。

在 Go 应用中集成 Prometheus 监控,核心是暴露符合规范的指标端点,并让 Prometheus 主动拉取。报警则由独立的 Alertmanager 配合 Prometheus 的告警规则实现,Go 本身不直接处理报警逻辑。
使用官方客户端库 prometheus/client_golang,最简方式是注册默认指标并启动 HTTP 服务:
import "github.com/prometheus/client_golang/prometheus/promhttp"
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
这样访问 http://localhost:8080/metrics 就能看到基础运行时指标(如 Go goroutines 数、内存分配等)。
按需定义指标变量并注册到默认注册器:
立即学习“go语言免费学习笔记(深入)”;
httpRequestsTotal := prometheus.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total", Help: "Total HTTP Requests"}, []string{"method", "status"})
httpRequestDuration := prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "http_request_duration_seconds", Help: "HTTP request duration in seconds"}, []string{"handler"})
.WithLabelValues("GET", "200").Inc() 或 .WithLabelValues("api").Observe(latency)
注意:所有自定义指标必须在程序启动早期注册,否则采集不到。
修改 Prometheus 配置文件 prometheus.yml,添加 job:
static_configs: - targets: ["your-go-app:8080"]
labels: app: "user-service"
curl -X POST http://localhost:9090/-/reload)之后在 Prometheus Web UI 的 Targets 页面确认状态为 UP,Graph 页面输入 http_requests_total 即可查数据。
Prometheus 不直接发通知,而是把告警推给 Alertmanager:
prometheus.yml 中配置 rule_files 和 alerting(指向规则文件路径)alerts.yml,写规则,例如:IF http_requests_total{job="user-service"}
alerting: alertmanagers: - static_configs: - targets: ["localhost:9093"]
规则触发后,Alertmanager 负责去重、分组、静默和通知发送。
基本上就这些。Go 侧只管暴露指标,其余交给 Prometheus 生态。不复杂但容易忽略注册时机和路径一致性。
以上就是如何在Golang中监控云原生应用_使用Prometheus采集指标和报警的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号