Sobes.tech
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:

  1. In the Go application, connect the Prometheus client library (prometheus/client_golang).
  2. Define and register metrics (counters, histograms, gauges).
  3. Start an HTTP server with the /metrics endpoint, which provides the current metric values in a format understandable by Prometheus.
  4. Configure Prometheus to scrape metrics from this endpoint.
  5. 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.