This is an example code written with the progamming language go, that exposes metrics to prometheus. In this post under prometheus configuration, you can see the highighted text saying that you should have an application running, that exposes metrics to prometheus, so this is one of many possibilities.
We need 2 files:
-
main.go, which is the start of our code
- We are using the framework iris for the webservice
- We take advantage of the prometheus middleware of iris to pass the data into /metrics
-
collector.go, where we implement the heart of the task
As the name already teels us, we goal is here to collect the data, that we want to expose. We are using the go library for prometheus.There are 4 main tasks in there:
- Definition of the collector
type MyCollector struct {
myFirstMetric *prometheus.Desc
mySecondMetric *prometheus.Desc
// all metrics you want
}
- Contructor of the collector
func NewCollector() *MyCollector {
return &MyCollector{
myFirstMetric: prometheus.NewDesc("first_metric",
"description of first_metric",
nil, nil,
),
...
}
}
- Writting each collector into prometheus channel
func (collector *MyCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- collector.myFirstMetric
ch <- collector.mySecondMetric
...
}
- Collecting the metrics and update each channel
func (collector *MyCollector) Collect(ch chan<- prometheus.Metric) {
// implement the logic giving us the value, that we want to expose, here I just took an example
// those value could be from kafka or simple database
//Write latest value for each metric in the prometheus metric channel.
ch <- prometheus.MustNewConstMetric(collector.myFirstMetric, prometheus.CounterValue, firstValue)
ch <- prometheus.MustNewConstMetric(collector.mySecondMetric, prometheus.CounterValue, secondValue)
}
go run main.go collector.go
Enter http://localhost:8080/metrics in your browser, you should get something like this
# HELP first_metric description of first_metric
# TYPE first_metric counter
first_metric 1
# HELP go_gc_duration_seconds A summary of the GC invocation durations.
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 0.0049994
go_gc_duration_seconds{quantile="0.25"} 0.0049994
go_gc_duration_seconds{quantile="0.5"} 0.0049994
go_gc_duration_seconds{quantile="0.75"} 0.0049994
go_gc_duration_seconds{quantile="1"} 0.0049994
go_gc_duration_seconds_sum 0.0049994
go_gc_duration_seconds_count 1
...
# HELP second_metric description of second_metric
# TYPE second_metric counter
second_metric 2
As you see, first_metric and second_metric are listed in there. Note that the other metrics are automatically generated by the prometheus golang library. If you have a running prometheus, your prometheus will make a call periodically to your application. Read this for more.