Junior — Middle
Kuidas edastada rakenduse mõõdikud Grafana visualiseerimiseks ja jälgimiseks?
sobes.tech AI
Vastus AI-lt
To transmit metrics from a Go application to Grafana, the Prometheus monitoring system is commonly used, which integrates well with Grafana.
Main steps:
- In the Go application, connect the Prometheus client library (prometheus/client_golang).
- Define and register metrics (counters, histograms, gauges).
- Start an HTTP server with the
/metricsendpoint, which provides the current metric values in a format understandable by Prometheus. - Configure Prometheus to scrape metrics from this endpoint.
- Grafana connects to Prometheus as a data source and visualizes the metrics.
Example code in Go:
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
opsProcessed = prometheus.NewCounter(prometheus.CounterOpts{
Name: "myapp_processed_ops_total",
Help: "Total number of processed events",
})
)
func init() {
prometheus.MustRegister(opsProcessed)
}
func main() {
http.Handle("/metrics", promhttp.Handler())
go func() {
for {
opsProcessed.Inc() // increment the counter
time.Sleep(time.Second)
}
}()
http.ListenAndServe(":2112", nil)
}
This way, metrics become available for collection by Prometheus and visualization in Grafana.