Go微服务监控核心是采集请求级和系统级指标并标准化暴露给Prometheus;推荐用net/http/pprof、prometheus/client_golang和HTTP中间件实现,包括请求计时与状态码统计、pprof运行时分析、OpenTelemetry分布式追踪联动及/metrics端点暴露。

在 Go 微服务中做监控,核心是采集请求级和系统级指标,并通过标准化方式暴露给 Prometheus 等监控系统。不需要重造轮子,用好 net/http/pprof、prometheus/client_golang 和中间件即可快速落地。
为每个 HTTP handler 添加计时、状态码、路径维度的统计,是最直接的请求监控方式。推荐使用 promhttp + 自定义中间件:
prometheus.NewCounterVec 统计请求数,NewHistogramVec 记录响应耗时(建议按 path 和 status 分桶)[]float64{0.01, 0.05, 0.1, 0.2, 0.5, 1, 2, 5},单位秒)net/http/pprof 是 Go 官方提供的运行时分析接口,适合排查 CPU、内存、goroutine 等问题:
http.HandleFunc("/debug/pprof/", pprof.Index),默认启用 goroutine、heap、threadcreate 等端点http.ListenAndServe("127.0.0.1:6060", nil))prometheus-pusher 或自研 exporter 抓取 /debug/pprof/ 数据并转为指标(如 goroutines 数量)当微服务调用链变长,单纯 HTTP 指标不够,需关联请求 ID、上下游耗时、错误传播路径:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
193
立即学习“go语言免费学习笔记(深入)”;
go.opentelemetry.io/otel,用 otelhttp.NewHandler 包装 handler,自动注入 trace contextprometheus.Exporter,把 trace 中的 latency、error_count 等同步写入 Prometheus 指标(例如:每条 trace 结束时更新 http_server_duration_seconds)ParentBased(TraceIDRatioBased(0.01)) 控制 1% 采样率所有指标最终要统一暴露给 Prometheus 抓取:
promhttp.Handler() 到 /metrics 路由,确保返回标准文本格式(Content-Type: text/plain; version=0.0.4)scrape_interval: 15s)不复杂但容易忽略。关键不是堆功能,而是让指标真正可查、可告警、可归因。
以上就是如何在Golang中实现微服务监控_统计请求和性能指标的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号