英文:
How to pull metrics in prometheus using client_golang
问题
我正在尝试使用GoLang编写一个JSON导出器,使用client_golang库。
我找不到任何有用的示例。我有一个名为ABC的服务,它通过HTTP生成JSON输出。我想使用client-golang库将这个指标导出到Prometheus。
英文:
I am trying to write a JSON exporter in GoLang using client_golang
I could not find any useful example for this. I have a service ABC that produces JSON output over HTTP. I want to use the client-golang to export this metric to prometheus.
答案1
得分: 3
请查看Go客户端的godoc,它非常详细,并包含大量示例。这里最相关的是Collector接口的文档:
https://godoc.org/github.com/prometheus/client_golang/prometheus#example-Collector
基本上,你需要实现Collector接口,它包含两个方法:describe
和collect
。
describe
方法通过给定的通道发送Collector可能的指标的描述。这包括它们的名称、可能的标签值和帮助字符串。
collect
方法创建与describe
中描述匹配的实际指标,并用数据填充它们。所以在你的情况下,它会从你的服务中获取JSON数据,解析它,并将值写入相关的指标。
在你的main
函数中,你需要注册你的collector,并启动HTTP服务器,代码如下:
prometheus.MustRegister(NewCustomCollector())
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
英文:
Take a look at the godoc for the Go client, it is very detailed and contains plenty of examples. The one for the Collector interface is probably the most relevant here:
https://godoc.org/github.com/prometheus/client_golang/prometheus#example-Collector
Essentially, you would implement the Collector interface, which contains two methods: describe
and collect
.
describe
simply sends descriptions for the possible Metrics of your Collector over the given channel. This includes their name, possible label values and help string.
collect
creates actual metrics that match the descriptions from describe
and populates them with data. So in your case, it would GET the JSON from your service, unmarshal it, and write values to the relevant metrics.
In your main
function, you then have to register your collector, and start the HTTP server, like this:
prometheus.MustRegister(NewCustomCollector())
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
答案2
得分: 1
你的意思是你想使用golang为自己的服务编写一个导出器?Prometheus导出器页面上列出的导出器都是很好的示例,其中许多是用golang编写的,你可以选择一个简单的,比如redis导出器,看看它是如何实现的。
基本上你需要做以下几步:
- 定义自己的
Exporter
类型 - 实现接口prometheus.Collector,你可以从你的服务中获取JSON数据并基于它构建指标
- 通过prometheus.MustRegister将你自己的
Exporter
注册到Prometheus中 - 启动一个HTTP服务器,并暴露指标的端点供Prometheus获取指标
英文:
You mean you want to write an exporter for your own service using golang? The exporters listed on prometheus exporter page are all good examples, many of which are written in golang, you could pick a simple one like redis exporter to see how it's implemented.
Basically what you need to do is:
- Define your own
Exporter
type - Implement interface prometheus.Collector, you can poll the json data from your service and build metrics based on it
- Register your own
Exporter
to prometheus by prometheus.MustRegister - Start a HTTP server and expose metrics endpoint for prometheus to poll metrics
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论