首页 > 后端开发 > Golang > 正文

Golang如何实现Prometheus自定义指标采集

P粉602998670
发布: 2025-11-08 23:16:02
原创
888人浏览过
答案是通过引入Prometheus client_golang库,在Go项目中定义、注册并更新自定义指标,再通过HTTP暴露/metrics端点供Prometheus抓取。具体步骤包括:1. 安装client_golang库;2. 使用Counter、Gauge等类型定义业务指标;3. 在init函数中注册指标;4. 于业务逻辑中更新指标值;5. 通过promhttp.Handler()暴露metrics接口;6. 配置Prometheus目标抓取该端点,最终实现监控数据采集与查询。

golang如何实现prometheus自定义指标采集

在Go项目中接入Prometheus自定义指标采集,核心是使用官方提供的 client_golang 库暴露业务相关的监控数据。整个过程包括定义指标、注册、更新数值,并通过HTTP服务暴露给Prometheus抓取。

1. 引入Prometheus客户端库

安装Go的Prometheus客户端:

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

这两个包分别用于定义指标和提供HTTP处理器来暴露指标。

2. 定义自定义指标

Prometheus支持多种指标类型:Counter(计数器)、Gauge(当前值)、Histogram(直方图)、Summary(摘要)。根据业务场景选择合适类型。

立即学习go语言免费学习笔记(深入)”;

例如,定义一个请求计数器和一个处理耗时的直方图:

var (
  httpRequestsTotal = prometheus.NewCounterVec(
    prometheus.CounterOpts{
      Name: "http_requests_total",
      Help: "Total number of HTTP requests made.",
    },
    []string{"method", "endpoint", "status"},
  )

  requestDuration = prometheus.NewHistogramVec(
    prometheus.HistogramOpts{
      Name: "http_request_duration_seconds",
      Help: "HTTP request latency in seconds.",
      Buckets: prometheus.DefBuckets,
    },
    []string{"method", "endpoint"},
  )
)

3. 注册指标

定义后的指标需要注册到默认的Registry中,才能被暴露出来:

func init() {
  prometheus.MustRegister(httpRequestsTotal)
  prometheus.MustRegister(requestDuration)
}

也可以创建自定义Registry,但通常使用默认即可。

标小兔AI写标书
标小兔AI写标书

一款专业的标书AI代写平台,提供专业AI标书代写服务,安全、稳定、速度快,可满足各类招投标需求,标小兔,写标书,快如兔。

标小兔AI写标书 40
查看详情 标小兔AI写标书

4. 在业务代码中更新指标

在处理HTTP请求的地方记录数据:

func handler(w http.ResponseWriter, r http.Request) {
  start := time.Now()

  // 模拟业务逻辑
  time.Sleep(100
time.Millisecond)

  // 更新计数器
  httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path, "200").Inc()

  // 更新耗时
  requestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(time.Since(start).Seconds())

  w.Write([]byte("OK"))
}

5. 暴露/metrics端点

启动一个HTTP服务,将指标通过 /metrics 接口暴露:

func main() {
  http.Handle("/metrics", promhttp.Handler())
  http.HandleFunc("/", handler)

  log.Println("Server starting on :8080")
  log.Fatal(http.ListenAndServe(":8080", nil))
}

启动后访问 http://localhost:8080/metrics 可看到类似如下内容:

# HELP http_requests_total Total number of HTTP requests made.
# TYPE http_requests_total counter
http_requests_total{endpoint="/",method="GET",status="200"} 5

6. 配置Prometheus抓取

在Prometheus配置文件中添加目标:

scrape_configs:
  - job_name: 'go-app'
    static_configs:
      - targets: ['localhost:8080']

重启Prometheus后,在Web UI中就能查询自定义指标。

基本上就这些。关键在于合理设计指标名称和标签,避免 cardinality 过高,同时确保性能开销可控。

以上就是Golang如何实现Prometheus自定义指标采集的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号