How to add go runtime metrics, with self-define label?
jencoldeng opened this issue · 3 comments
I use prom client juest like this:
`
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
// Serve the default Prometheus metrics registry over HTTP on /metrics.
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
`
It includes go runtime sdk. But how can I define my own label to each metric? Like serviceName, agentIp, and so on.
Ideally you add that on collection side (e.g. Prometheus relabelling), so your application is portable (it allows changing service name easily).
If you really what to do this in process, you can use https://pkg.go.dev/github.com/prometheus/client_golang/prometheus#WrapRegistererWith with custom registry (recommended option, we are moving away from prometheus.DefaultRegisterer
due to global var).
Example:
// A minimal example of how to include Prometheus instrumentation.
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
func main() {
flag.Parse()
// Create a new registry.
reg := prometheus.NewRegistry()
prometheus.WrapRegistererWith(prometheus.Labels{"serviceName": "yolo"}, reg).MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
// Expose the registered metrics via HTTP.
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
log.Fatal(http.ListenAndServe(*addr, nil))
}
Leaving this open as a todo to add the above to the examples, help wanted!
It Solved ! thanks !~