golang 的 expvar 包可结合 prometheus 实现轻量级监控。1. expvar 是 go 标准库包,默认暴露内存分配、gc 次数、goroutine 数量等指标,并支持注册自定义变量;2. prometheus 通过 expvar_exporter 中间件转换 json 数据为文本格式抓取;3. 也可在服务中内置适配器,手动遍历变量并按 prometheus 格式输出;4. 注意路径冲突、安全限制、性能影响及指标命名规范等问题。

Golang 的
expvar
expvar

expvar
/debug/vars
你可以手动注册自定义变量,例如计数器、状态值等,这些都可以被 Prometheus 抓取。
立即学习“go语言免费学习笔记(深入)”;

使用示例:
import (
"expvar"
"net/http"
)
var myCounter = expvar.NewInt("my_custom_counter")
func main() {
http.ListenAndServe(":8080", nil)
}访问
http://localhost:8080/debug/vars

{
"cmdline": [...],
"memstats": {...},
"my_custom_counter": 0
}Prometheus 本身不能直接解析
expvar
expvar_exporter
你可以用社区提供的工具如 expvar_exporter
/debug/vars
配置方式:
/debug/vars
expvar_exporter
go install github.com/justwatchcom/gosr/cmd/expvar_exporter@latest expvar_exporter -listen :8081 -url http://localhost:8080/debug/vars
http://localhost:8081/metrics
Prometheus 配置抓取:
scrape_configs:
- job_name: 'myapp'
static_configs:
- targets: ['localhost:8081']这样就完成了基本集成。
如果你希望不引入额外组件,也可以自己写一个适配器,将
expvar
思路如下:
expvar
# HELP my_custom_counter Custom counter. # TYPE my_custom_counter gauge my_custom_counter 42
这种方式适合嵌入到已有服务中,不需要额外部署中间件。
/debug/vars
expvar
基本上就这些了。用
expvar
以上就是Golang的expvar如何暴露运行时指标 集成Prometheus监控方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号