Golang prometheus exporter for timestamped metrics

jboothomas
1 min readFeb 22, 2023

Posting this quick code snippet for those who may be looking to export metrics with a timestamp for scraping by prometheus.

This can be useful when parsing metrics that are provided with a certain “lag”, that we still want visible within prometheus -> grafana.

const (
timelayout = "2006-01-02 15:04:05"
)

type timedCollector_NAME struct {
timedMetric *prometheus.Desc
}

func (collector *timedCollector_NAME) Describe(ch chan<- *prometheus.Desc) {
ch <- collector.timedMetric
}

func newCollector_NAME() *timedCollector_NAME{
return &timedCollector_NAME{
timedMetric: prometheus.NewDesc(
"metric_exporter_name",
"Description of the metric",
[]string{"extravalue1","extravalue2","extravalueN",}, nil,
),
}
}

func (collector *timedCollector_NAME) Collect(ch chan<- prometheus.Metric){
metric_value, _ := 123 //inset logic required to give the value needed
mytimevalue := time.Now() //insert logic to get date time for the metric
timeReportedByExternalSystem := time.Parse(timelayout, mytimevalue)
if err != nil {
log.Println(err)
}
extravalue1 := "thisvalue1"
extravalue2 := "thisvalus2"
extravalueN := "thisvalueN"
ch <- prometheus.NewMetricWithTimestamp(
timeReportedByExternalSystem,
prometheus.MustNewConstMetric(
collector.timedMetric, prometheus.GaugeValue, metric_value, extravalue1, extravalue2, extravalueN,
),
)
}


func main() {
r := prometheus.NewRegistry()

timedNAME := newCollector_NAME()
r.MustRegister(timedNAME)

rhandler := promhttp.HandlerFor(r, promhttp.HandlerOpts{})
http.Handle("/metrics", r)
http.ListenAndServe(":8080", nil)
log.Println("[debug] running metrics on port 8080")
}

It is possible to add as many timed metrics as required. You just need the structure, Describe, Collect and metrics description functions for each time stamped metric you wish to add. Remember to add each newCollector to the main function and register it to the correct httpHandle.

I hope this helps anyone trying to establish timestamped metrics.

--

--

jboothomas

Infrastructure engineering for modern data applications