As defined in the prometheus documentation, when writing exporters it states the following:
Metrics should only be pulled from the application when Prometheus scrapes them, exporters should not perform scrapes based on their own timers.
The following code technically works fine, and publishes an appropriate page with my custom metric. So it solves my business need as-is.
However, it is inefficient and running an infinite loop to constantly update the value. This does not match the above mentioned practice from the documentation of only generating metric values when Prometheus scrapes.
package main
import (
"log"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
var metricSystemTime = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "custom_system_time", Help: "Timestamp in unix epoch format"})
prometheus.MustRegister(metricSystemTime)
go startServer()
for {
metricSystemTime.Set(float64(time.Now().Unix()))
time.Sleep(1 * time.Second)
}
}
func startServer() {
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":19100", nil))
}
In order to only pull metrics when prometheus scrapes the exporter endpoint, that means I need to somehow listen for GET requests on the http.ListenAndServe() object? How can I do that?
In my reading I found http.HandlerFunc() instead of http.Handler() which seems to be going down the right path, but I can't get it to work with promhttp.Handler() and I'm getting pretty lost on it.