3 客户端说明

  • 下载客户端包

go get github.com/prometheus/client_golang
  • 包结构

.
├── api
   └── prometheus
       └── v1                     # Prometheus服务端HTTP API客户端
           ├── 实现PromQL查询接口(/api/v1/query)
           ├── 告警规则管理接口(/api/v1/rules)
           └── 元数据查询接口(/api/v1/targets)


├── examples                       # 场景化示例库
   ├── createdtimestamps          # 展示自定义指标时间戳生成
   ├── customlabels               # 动态标签管理最佳实践
   ├── exemplars                  # 分布式追踪采样点(Exemplars)集成示例
   ├── gocollector                # Go运行时指标收集器集成
   ├── middleware                 # 监控中间件
      └── httpmiddleware         # HTTP全链路监控(RED指标)实现
   ├── random                     # 多分布类型指标生成器
      └── 模拟RPC延迟(均匀/正态/指数分布)
   ├── simple                     # 最简指标埋点示例
   └── versioncollector          # 应用版本信息采集(如Git Commit)


├── exp                            # 实验性功能模块
   ├── api
      └── remote
          └── genproto
              └── v2            # 实验性远程写入协议(Remote Write)V2
                  ├── 跨平台序列化协议
                  └── 高性能二进制编码
   └── internal
       └── github.com            # 实验性依赖库
           ├── efficientgo
              └── core
                  └── backoff    # 指数退避算法实验实现
           └── planetscale
               └── vtprotobuf     # Protobuf高效编解码器
                   └── protohelpers # Protobuf工具链增强


├── internal                       # 内部实现细节(用户不应直接调用)
   └── github.com
       └── golang
           └── gddo
               └── httputil
                   └── header     # HTTP头处理工具(如Accept-Encoding解析)


├── prometheus                     # 核心模块
   ├── collectors
      └── version              # 语义化版本指标转换器(如将"v1.2.3"转为数值指标)
   ├── graphite                 # Graphite协议桥接器
      └── 实现Prometheus→Graphite协议转换
   ├── internal                 # 核心内部工具
   ├── promauto                 # 自动注册工厂
      └── 零配置指标注册(如NewCounter自动挂载到默认注册表)
   ├── promhttp                 # HTTP协议适配
      ├── internal            # HTTP处理器内部逻辑
      └── zstd               # Zstandard压缩支持(替代gzip)
   ├── push                    # Pushgateway推送管道
   └── testutil                # 测试工具
       └── promlint            # 指标命名规范校验器
           └── validations     # 校验规则(如禁止使用保留标签名)


└── tutorials                     # 教学案例
    └── whatsup                  # 端到端可观测性样板工程
        ├── internal            # 业务逻辑
        └── reference           # 参考架构文档
            ├── 日志-指标-追踪三支柱实现
            └── SLO/SLA监控样板

1. ​github.com/prometheus/client_golang/prometheus

​核心作用​​:

  • ​指标类型定义​​:Counter(计数器)、Gauge(仪表盘)、Histogram(直方图)、Summary(摘要)

  • ​标签管理​​:*Vec 类型(如 CounterVec)实现多维度标签

  • ​注册中心​​:Registry 管理指标的注册与生命周期

  • ​自定义收集器​​:实现 Collector 接口(适用于复杂指标采集逻辑)

​典型场景​​:

// 定义带标签的指标
httpReqs := prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "http_requests_total",
        Help: "Total HTTP requests",
    },
    []string{"method", "path"},
)

// 实现自定义收集器(如采集第三方系统指标)
type MyCollector struct{...}
func (c *MyCollector) Describe(ch chan<- *prometheus.Desc) {...}
func (c *MyCollector) Collect(ch chan<- prometheus.Metric) {...}

2. ​**github.com/prometheus/client_golang/prometheus/collectors​**​

​核心作用​​:

  • ​预置系统指标采集器​​:

    • NewGoCollector():采集 Go 运行时指标(GC、协程等)

    • NewProcessCollector():采集进程资源(CPU、内存、FD 等)

​典型场景​​:

// 注册 Go 运行时和进程指标
registry := prometheus.NewRegistry()
registry.MustRegister(
    collectors.NewGoCollector(),
    collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)

3. ​github.com/prometheus/client_golang/prometheus/promhttp

​核心作用​​:

  • ​暴露 HTTP 端点​​:生成 /metrics 端点处理器

  • ​性能优化​​:自动处理并发、压缩和协议协商

​典型场景​​:

// 启动 HTTP 服务暴露指标
http.Handle("/metrics", promhttp.HandlerFor(
    registry,
    promhttp.HandlerOpts{},
))
http.ListenAndServe(":8080", nil)

4. ​github.com/prometheus/client_golang/prometheus/promauto

​核心作用​​:

  • ​自动注册指标​​:简化指标创建与注册流程

  • ​零配置快速集成​​:自动注册到默认注册表

​典型场景​​:

// 自动注册计数器
opsProcessed := promauto.NewCounter(prometheus.CounterOpts{
    Name: "myapp_processed_ops_total",
    Help: "Total processed operations",
})

5. ​github.com/prometheus/client_golang/push

​核心作用​​:

  • ​Pushgateway 集成​​:推送指标到网关

  • ​批处理/短期任务​​:适合无法长期运行的服务

​典型场景​​:

pusher := push.New("http://pushgateway:9091", "my_job")
pusher.Collector(registry)
pusher.Push()

6. ​github.com/prometheus/client_golang/prometheus/testutil

​核心作用​​:

  • ​测试工具​​:验证指标值是否符合预期

  • ​指标规范校验​​:检查命名/标签合规性

​典型场景​​:

// 测试计数器值是否正确
if err := testutil.CollectAndCompare(counter, strings.NewReader(`
    # HELP http_requests_total Total HTTP requests
    # TYPE http_requests_total counter
    http_requests_total{method="GET"} 5
`)); err != nil {
    t.Fatal(err)
}

最后更新于