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

Golang如何使用Prometheus监控应用

P粉602998670
发布: 2025-10-15 14:20:02
原创
534人浏览过
Go应用通过prometheus/client_golang库集成Prometheus监控,首先引入包并定义Counter、Gauge、Histogram指标,如请求总数和响应延迟;接着在init函数中注册指标,使用中间件记录HTTP请求的method和endpoint维度数据;然后通过http.Handle("/metrics", promhttp.Handler())暴露指标接口;最后在Prometheus配置中添加目标地址,实现定时抓取,结合Grafana可完成可视化监控。

golang如何使用prometheus监控应用

Prometheus 是云原生生态中最流行的监控系统之一,Golang 应用可以很方便地集成 Prometheus 来暴露指标数据。实现方式主要是通过 prometheus/client_golang 官方库,在应用中定义并暴露 HTTP 接口供 Prometheus 抓取。

引入 Prometheus 客户端库

在 Go 项目中使用 Prometheus,第一步是引入官方客户端库:

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

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

定义并注册监控指标

你可以根据需要创建计数器(Counter)、仪表(Gauge)、直方图(Histogram)等类型的指标。例如,统计请求次数和响应耗时:

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

Counter:只增不减,适合累计值,如请求数。
Gauge:可增可减,适合当前状态,如内存使用量。
Histogram:记录分布,如请求延迟。

示例代码:

package main

import ( "net/http" "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"}, )

httpRequestDuration = prometheus.NewHistogramVec(
    prometheus.HistogramOpts{
        Name:    "http_request_duration_seconds",
        Help:    "HTTP request latency in seconds.",
        Buckets: []float64{0.1, 0.3, 0.5, 1.0, 3.0},
    },
    []string{"method", "endpoint"},
)
登录后复制

)

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

在 HTTP 路由中记录指标

使用中间件的方式,在每个请求前后记录指标。以下是一个简单的日志+监控中间件:

Kits AI
Kits AI

Kits.ai 是一个为音乐家提供一站式AI音乐创作解决方案的网站,提供AI语音生成和免费AI语音训练

Kits AI 413
查看详情 Kits AI
func monitor(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now()
    // 执行实际处理逻辑
    next.ServeHTTP(w, r)

    // 请求结束后记录指标
    httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc()
    httpRequestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(time.Since(start).Seconds())
}
登录后复制

}

func helloHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) }

将 handler 包装进中间件:

http.HandleFunc("/hello", monitor(helloHandler))

暴露 /metrics 接口供 Prometheus 抓取

Prometheus 通过定期抓取目标的 /metrics 接口获取指标数据。你需要添加一个路由来暴露这些指标:

http.Handle("/metrics", promhttp.Handler())

启动服务:

func main() { http.ListenAndServe(":8080", nil) }

运行程序后,访问 https://www.php.cn/link/c219b83bdbd3fc9bf4fa8526d4368ea1 可看到类似以下内容:

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

HELP http_request_duration_seconds HTTP request latency in seconds.

TYPE http_request_duration_seconds histogram

http_request_duration_seconds_bucket{endpoint="/hello",method="GET",le="0.1"} 3 ...

Prometheus 配置抓取任务

prometheus.yml 中添加你的 Go 应用为目标:

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

确保 Prometheus 能访问你的应用地址。重启 Prometheus 后,可在 Web 界面查看抓取到的指标。

基本上就这些。Go 应用通过简单几行代码就能接入 Prometheus,配合 Grafana 可实现可视化监控。关键是定义好有意义的指标,并持续优化观测维度。

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