Prometheus 指标在 Go (Golang) 中:监控完全指南

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

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

开始课程

Prometheus 指标在 Go (Golang) 中:完全指南



Prometheus 是一个开源监控系统,已成为现代微服务架构中收集和分析指标的事实标准。在 Go (Golang) 生态系统中,prometheus/client_golang 库为应用程序仪表化提供了强大而灵活的工具集。在本文中,我们将详细讨论如何将 Prometheus 指标添加到您的 Go 应用程序中,配置 HTTP 端点,并创建自定义指标类型。



安装与配置



首先,您需要安装官方的 Prometheus Go 客户端:



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


第一个库提供了创建和注册指标的核心功能,第二个库则为 /metrics 端点提供了现成的 HTTP 处理器。



Prometheus 基本指标类型



Prometheus 支持四种主要指标类型,每种类型都用于解决特定问题:



  • Counter (计数器) — 单调递增的值。非常适合统计请求数量、错误次数、已完成任务数。
  • Gauge (测量仪) — 可以增加或减少的值。用于当前温度、活跃连接数、队列大小。
  • Histogram (直方图) — 收集观测值(例如请求执行时间)并将其分组到可配置的“桶”(buckets)中。允许计算分位数。
  • Summary (摘要) — 类似于直方图,但在应用程序端计算分位数。适用于分位数对业务逻辑至关重要的情况。


实践示例:带指标的 HTTP 服务器



让我们创建一个简单的 Web 应用程序,用于记录请求数量、请求持续时间以及当前活跃连接数。



package main

import ( "fmt" "net/http" "time"

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

var ( // 带有 "method" 和 "endpoint" 标签的请求计数器 requestCounter = 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 duration in seconds", Buckets: prometheus.DefBuckets, // [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10] }, []string{"method", "endpoint"}, )

// 活跃连接测量仪 activeConnections = prometheus.NewGauge( prometheus.GaugeOpts{ Name: "http_active_connections", Help: "Current number of active connections", }, ))

func init() { // 在 Prometheus 注册表中注册指标 prometheus.MustRegister(requestCounter) prometheus.MustRegister(requestDuration) prometheus.MustRegister(activeConnections)}

// middleware 包装每个 HTTP 请求以收集指标func metricsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 增加活跃连接计数器 activeConnections.Inc() defer activeConnections.Dec()

start := time.Now() next.ServeHTTP(w, r) duration := time.Since(start).Seconds()

// 记录请求指标 requestCounter.WithLabelVal

推荐