How do I export metrics with Prometheus in Go?

In this guide, we'll go over how to export metrics with Prometheus in a Go application. Prometheus is a powerful monitoring tool that collects metrics from configured targets at specified intervals. To get started, we will implement a simple HTTP server in Go that exports metrics for Prometheus to scrape.

First, ensure you have the Prometheus Go client library installed:

go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp

Below is an example of a basic Go application that exports a simple counter metric:

package main

import (
    "net/http"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
    // Create a new counter metric
    requestsCounter = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "Total number of HTTP requests",
        },
        []string{"method"},
    )
)

func init() {
    // Register the counter with Prometheus
    prometheus.MustRegister(requestsCounter)
}

func handler(w http.ResponseWriter, r *http.Request) {
    // Increment the counter
    requestsCounter.WithLabelValues(r.Method).Inc()
    w.Write([]byte("Hello, World!"))
}

func main() {
    // Set up the metrics endpoint
    http.Handle("/metrics", promhttp.Handler())
    http.HandleFunc("/", handler)

    // Start the HTTP server
    http.ListenAndServe(":8080", nil)
}

After running the application, you can access the metrics at /metrics endpoint. Make sure to configure your Prometheus server to scrape this endpoint to collect the metrics.


Go Prometheus metrics monitoring HTTP server Go application metrics export