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

Golang Prometheus监控指标收集示例

P粉602998670
发布: 2025-10-05 09:01:01
原创
226人浏览过
首先引入Prometheus客户端库,定义并注册计数器和直方图指标,通过HTTP Handler记录请求量和耗时,暴露/metrics接口供Prometheus抓取,最后在配置文件中添加目标地址实现监控。

golang prometheus监控指标收集示例

在Go语言中使用Prometheus进行监控指标收集非常常见,尤其适合微服务和高并发场景。下面是一个简单的Golang程序示例,展示如何暴露HTTP接口供Prometheus抓取自定义指标。

1. 引入依赖

使用官方Prometheus客户端库来创建和暴露指标:

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

2. 定义并注册监控指标

可以在程序中定义计数器、直方图、仪表盘等常用指标。以下是一个包含计数器和直方图的示例:

代码示例:

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

幻舟AI
幻舟AI

专为短片创作者打造的AI创作平台

幻舟AI 279
查看详情 幻舟AI
package main

import (
  "net/http"
  "math/rand"
  "time"
  "github.com/prometheus/client_golang/prometheus"
  "github.com/prometheus/client_golang/prometheus/promhttp"
)

// 定义两个指标
var (
  httpRequestsTotal = prometheus.NewCounterVec(
    prometheus.CounterOpts{
      Name: "http_requests_total",
      Help: "Total number of HTTP requests.",
    },
    []string{"method", "endpoint"},
  )

  requestDuration = prometheus.NewHistogram(
    prometheus.HistogramOpts{
      Name: "http_request_duration_seconds",
      Help: "HTTP request duration in seconds.",
      Buckets: prometheus.DefBuckets,
    },
  )
)

func init() {
  // 注册指标到默认的Registry
  prometheus.MustRegister(httpRequestsTotal)
  prometheus.MustRegister(requestDuration)
}

// 模拟处理请求的Handler
func handler(w http.ResponseWriter, r *http.Request) {
  start := time.Now()
  httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc()

  // 模拟一些处理延迟
  time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)

  w.WriteHeader(http.StatusOK)
  w.Write([]byte("Hello, Prometheus!"))

  // 记录请求耗时
  requestDuration.Observe(time.Since(start).Seconds())
}

func main() {
  http.HandleFunc("/hello", handler)

  // 暴露/metrics端点供Prometheus抓取
  http.Handle("/metrics", promhttp.Handler())

  http.ListenAndServe(":8080", nil)
}

3. 配置Prometheus抓取目标

启动上面的Go程序后,访问 http://localhost:8080/metrics 可看到类似以下输出:

# HELP http_requests_total Total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{endpoint="/hello",method="GET"} 3

# HELP http_request_duration_seconds HTTP request duration in seconds.
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_sum 0.423
http_request_duration_seconds_count 3

编辑Prometheus配置文件(prometheus.yml)添加Job:

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

重启Prometheus后,在Web UI中即可查询 http_requests_totalhttp_request_duration_seconds 等指标。

4. 常用指标类型说明

  • Counter(计数器):只增不减,适合记录请求数、错误数等
  • Gauge(仪表盘):可增可减,适合内存使用、在线用户数等
  • Histogram(直方图):记录样本分布,如请求延迟分桶统计
  • Summary(摘要):类似直方图,但支持计算分位数

基本上就这些。只要在程序中正确注册指标并暴露/metrics接口,Prometheus就能自动抓取数据。实际项目中建议结合中间件统一收集HTTP指标,避免重复埋点。

以上就是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号