如何使用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.

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))

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:

  1. Define your own Exporter type
  2. Implement interface prometheus.Collector, you can poll the json data from your service and build metrics based on it
  3. Register your own Exporter to prometheus by prometheus.MustRegister
  4. Start a HTTP server and expose metrics endpoint for prometheus to poll metrics