Go 应用监控:库与工具

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Go (Golang) 应用监控:工具与库



监控是任何服务在生产环境中运行不可或缺的一部分。对于 Go (Golang) 应用,其生态系统既提供了内置解决方案,也提供了强大的外部工具。在本文中,我们将分析主要方法:从基础性能分析到指标收集和链路追踪。



1. 内置工具:expvar 包

expvar 包提供了一个最简单的 HTTP 端点,用于发布应用程序的状态变量。它不需要外部依赖,非常适合快速诊断。



集成与使用

package main

import ( "expvar" "net/http")

var requestsCount = expvar.NewInt("total_requests")

func handler(w http.ResponseWriter, r *http.Request) { requestsCount.Add(1) w.Write([]byte("OK"))}

func main() { http.HandleFunc("/api", handler) // /debug/vars 端点将自动可用 http.ListenAndServe(":8080", nil)}

启动后,访问 /debug/vars — 您将看到一个包含指标的 JSON,其中包括请求计数、GC 数据和内存信息。



2. Prometheus — 事实上的指标标准

Prometheus 是 Go 最流行的监控系统。prometheus/client_golang 库允许您以 Prometheus 服务器可理解的格式导出指标。



安装

go get github.com/prometheus/client_golang/prometheusgo get github.com/prometheus/client_golang/prometheus/promhttp


示例:计数器和直方图

package main

import ( "net/http" "time"

"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp")

var ( requestCount = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests", }, []string{"method", "endpoint"}, ) requestDuration = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "Histogram of request durations", Buckets: prometheus.DefBuckets, }, []string{"method"}, ))

func init() { prometheus.MustRegister(requestCount, requestDuration)}

func handler(w http.ResponseWriter, r *http.Request) { start := time.Now() requestCount.WithLabelValues(r.Method, r.URL.Path).Inc() w.Write([]byte("Hello")) requestDuration.WithLabelValues(r.Method).Observe(time.Since(start).Seconds())}

func main() { http.Handle("/metrics", promhttp.Handler()) http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil)}

Prometheus 将从 /metrics 端点收集指标。您可以基于这些数据在 Alertmanager 中添加告警。



3. 使用 pprof 进行性能分析

net/http/pprof 包为应用程序添加了用于 CPU、内存、协程和锁性能分析的端点。这是查找瓶颈不可或缺的工具。



快速开始

package main

import ( "log" "net/http" _ "net/http/pprof" // 注册处理器)

func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, pprof!")) }) log.Fatal(http.ListenAndServe(":6060", nil))}

现在可用的端点:

  • /debug/pprof/ — 性能分析列表
  • /debug/pprof/profile — CPU 性能分析
  • /debug/pprof/heap — 内存性能分析
  • /debug/pprof/goroutine — 协程堆栈

使用 go tool pprof 命令或可视化工具分析性能分析文件。

推荐