首先实现指标采集与健康检查,再集成Prometheus暴露HTTP请求计数和耗时,通过/healthz接口检测服务状态,结合定时器触发阈值告警,并使用zap记录结构化日志以联动监控分析。

服务监控与告警是微服务架构中不可或缺的一环。Golang 凭借其高并发、低延迟的特性,非常适合构建稳定可靠的监控系统。本文将介绍如何使用 Golang 实现基础的服务监控与告警功能,涵盖指标采集、健康检查、Prometheus 集成以及简单的告警触发机制。
集成 Prometheus 实现指标暴露
在微服务中,最常用的监控方案是 Prometheus + Grafana。Golang 官方提供了 prometheus/client_golang 库,方便我们暴露自定义指标。
以下是一个暴露 HTTP 请求计数和响应耗时的简单示例:
package mainimport ( "net/http" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp")
立即学习“go语言免费学习笔记(深入)”;
var ( httpRequestsTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests.", }, []string{"method", "endpoint", "status"}, )
httpRequestDuration = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "HTTP request latency in seconds.", Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0}, }, []string{"method", "endpoint"}, ))
立即学习“go语言免费学习笔记(深入)”;
func init() { prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpRequestDuration) }
func instrumentHandler(next http.HandlerFunc, endpoint string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now() next.ServeHTTP(w, r) duration := time.Since(start).Seconds()
// 假设状态码可以获取(需包装 ResponseWriter) httpRequestsTotal.WithLabelValues(r.Method, endpoint, "200").Inc() httpRequestDuration.WithLabelValues(r.Method, endpoint).Observe(duration) }}
func main() { http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/api/hello", instrumentHandler(func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("Hello, World!")) }, "/api/hello")) http.ListenAndServe(":8080", nil)}
启动服务后,访问 :8080/metrics 即可看到暴露的指标,Prometheus 可通过 scrape 配置抓取这些数据。
实现服务健康检查
微服务需要提供一个健康检查接口,供负载均衡器或监控系统调用。通常使用 /healthz 路由返回服务状态。
示例如下:
func healthz(w http.ResponseWriter, r *http.Request) {
// 可加入数据库连接、缓存等依赖检查
ctx, cancel := context.WithTimeout(r.Context(), 1*time.Second)
defer cancel()
// 示例:模拟依赖检查
if err := checkDatabase(ctx); err != nil {
http.Error(w, "Database unreachable", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))}
func checkDatabase(ctx context.Context) error {
// 模拟数据库 ping
time.Sleep(100 * time.Millisecond)
select {
case
// 注册路由
http.HandleFunc("/healthz", healthz)
Prometheus 或其他探针可定期请求该接口,判断服务是否存活。
基于阈值触发简单告警
虽然复杂告警建议交由 Alertmanager 处理,但在轻量场景中,也可在 Go 程序内实现基本告警逻辑。
例如,定时检查某个指标是否超过阈值并发送通知:
func startAlerting() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
// 示例:检查某指标(实际可通过 Prometheus API 查询)
currentQPS := getCurrentQPS()
if currentQPS > 1000 {
sendAlert("High QPS detected: " + fmt.Sprintf("%.2f", currentQPS))
}
}}
func sendAlert(message string) {
// 可集成邮件、钉钉、企业微信等
log.Printf("[ALERT] %s", message)
// 示例:调用 Webhook 发送告警
// http.Post(alertWebhookURL, "application/json", ...)
}
这种方式适合内部工具或过渡方案,生产环境推荐使用 Prometheus 的 Rule 配合 Alertmanager。
日志与监控结合
结构化日志有助于问题排查。使用 zap 或 logrus 记录关键操作,并结合 ELK 或 Loki 进行集中分析。
示例使用 zap 记录请求日志:
logger, _ := zap.NewProduction() defer logger.Sync()http.HandleFunc("/api/hello", func(w http.ResponseWriter, r *http.Request) { logger.Info("request received", zap.String("method", r.Method), zap.String("url", r.URL.Path), zap.String("client_ip", r.RemoteAddr), ) w.Write([]byte("Hello")) })
日志中包含结构字段,便于后续查询与告警关联。
基本上就这些。Golang 微服务监控的核心在于指标暴露、健康检查和告警联动。借助 Prometheus 生态,可以快速搭建一套实用的监控体系。不复杂但容易忽略的是细节处理,比如上下文超时、指标命名规范和日志结构一致性。










