Skip to content

Instantly share code, notes, and snippets.

@discordianfish
Created July 16, 2021 10:50
Show Gist options
  • Save discordianfish/4c1760cf0e41c98ba5136e6e55b3e49b to your computer and use it in GitHub Desktop.
Save discordianfish/4c1760cf0e41c98ba5136e6e55b3e49b to your computer and use it in GitHub Desktop.
package main
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/promlog"
"github.com/prometheus/exporter-toolkit/web"
)
type TranslatingGatherer struct {
prometheus.Gatherer
translations map[string]string
}
func (g TranslatingGatherer) Gather() ([]*dto.MetricFamily, error) {
mfs, err := g.Gatherer.Gather()
if err != nil {
return nil, err
}
for i, mf := range mfs {
v, ok := g.translations[*mf.Name]
if ok {
mf.Name = &v
}
}
return mfs, nil
}
var (
cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "cpu_temperature_current",
Help: "Current temperature of the CPU.",
})
hdFailures = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "disk_errors_total",
Help: "Number of hard-disk errors.",
},
[]string{"device"},
)
)
func main() {
var (
registry = prometheus.NewRegistry()
mux = http.NewServeMux()
server = http.Server{Handler: mux, Addr: ":8080"}
logger = promlog.New(&promlog.Config{})
v1 = TranslatingGatherer{registry, map[string]string{
"cpu_temperature_current": "cpu_temperature_celsius",
"disk_errors_total": "hd_errors_total",
}}
v2alpha1 = registry
)
cpuTemp.Set(23.5)
hdFailures.With(prometheus.Labels{"device": "/dev/sda"}).Add(42)
registry.MustRegister(cpuTemp)
registry.MustRegister(hdFailures)
mux.Handle("/metrics/v1", promhttp.HandlerFor(v1, promhttp.HandlerOpts{}))
mux.Handle("/metrics/v2alpha1", promhttp.HandlerFor(v2alpha1, promhttp.HandlerOpts{}))
if err := web.ListenAndServe(&server, "", logger); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment