Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add go runtime metrics, with self-define label? #1585

Open
jencoldeng opened this issue Aug 19, 2024 · 3 comments · May be fixed by #1626
Open

How to add go runtime metrics, with self-define label? #1585

jencoldeng opened this issue Aug 19, 2024 · 3 comments · May be fixed by #1626

Comments

@jencoldeng
Copy link

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.

@bwplotka
Copy link
Member

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))
}

@bwplotka
Copy link
Member

Leaving this open as a todo to add the above to the examples, help wanted!

@jencoldeng
Copy link
Author

It Solved ! thanks !~

@ying-jeanne ying-jeanne linked a pull request Sep 15, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants