Golang应用通过prometheus/client_golang暴露指标,Prometheus依据规则触发告警并发送至AlertManager,后者按配置路由通知;1. 代码中定义http_requests_total计数器并注册到默认收集器;2. Prometheus加载alert_rules.yml设置响应时间超0.5秒持续2分钟则告警;3. AlertManager将告警分组并通过邮件或钉钉机器人发送;4. 依次启动Go服务、Prometheus和AlertManager后,访问/metrics验证指标采集,Prometheus Alerts页面查看告警状态,触发firing时AlertManager执行通知。

在使用 Golang 构建微服务或后台系统时,集成 Prometheus 和 AlertManager 实现监控告警是常见的做法。Prometheus 负责采集指标并触发告警规则,而 AlertManager 则负责处理这些告警,比如去重、分组、静默和通知(如发送邮件、钉钉、企业微信等)。下面介绍如何在 Golang 项目中结合 Prometheus 客户端暴露指标,并配置 AlertManager 实现完整的告警流程。
1. Golang 中暴露 Prometheus 指标
要在 Golang 应用中支持 Prometheus 监控,需要引入官方的 prometheus/client_golang 库来暴露自定义或系统指标。
示例代码:
package mainimport ( "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" )
var ( // 定义一个计数器指标 httpRequestsTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests.", }, []string{"method", "endpoint"}, ) )
func init() { prometheus.MustRegister(httpRequestsTotal) }
func handler(w http.ResponseWriter, r *http.Request) { httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc() w.Write([]byte("Hello Prometheus!")) }
func main() { http.Handle("/metrics", promhttp.Handler()) http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
启动后访问 :8080/metrics 可看到指标输出,Prometheus 即可通过 scrape 配置拉取这些数据。
立即学习“go语言免费学习笔记(深入)”;
2. Prometheus 配置告警规则
Prometheus 通过 rule_files 定义告警规则,当条件满足时会将告警发送给 AlertManager。
创建告警规则文件 alert_rules.yml:
groups:
- name: example
rules:
- alert: HighRequestLatency
expr: rate(http_requests_duration_seconds_sum[5m]) / rate(http_requests_duration_seconds_count[5m]) > 0.5
for: 2m
labels:
severity: warning
annotations:
summary: "High latency on {{ $labels.instance }}"
description: "The average request latency is above 500ms."
在 prometheus.yml 中启用该规则:
rule_files: - "alert_rules.yml"告警发送到 AlertManager
alerting: alertmanagers:
- static_configs:
- targets: ['localhost:9093']
3. 配置 AlertManager 发送通知
AlertManager 接收来自 Prometheus 的告警事件,并根据配置进行路由和通知。
示例 alertmanager.yml 配置:
route: group_by: ['alertname', 'severity'] group_wait: 30s group_interval: 5m repeat_interval: 1h receiver: 'email-notifier'receivers:
- name: 'email-notifier'
email_configs:
- to: 'admin@example.com' from: 'alertmanager@example.com' smarthost: 'smtp.example.com:587' auth_username: 'alertmanager@example.com' auth_password: 'password' require_tls: true
也可配置钉钉、企业微信等 webhook,例如使用钉钉机器人:
4. 启动服务并验证告警流程
依次启动以下组件:
- 运行 Golang 应用:
go run main.go - 启动 Prometheus:
./prometheus --config.file=prometheus.yml - 启动 AlertManager:
./alertmanager --config.file=alertmanager.yml
访问 Prometheus Web UI(默认 9090),在 Alerts 标签页查看是否触发告警。当告警状态变为 firing,AlertManager 会收到通知并按配置发送消息。
基本上就这些。Golang 暴露指标 + Prometheus 报警规则 + AlertManager 通知,构成了一个完整、可扩展的告警体系。实际生产中建议加入 TLS、认证、多级通知策略和静默管理,提升稳定性与可用性。










