Instrumenting Any Application for Custom metric using Prometheus.

Shubham Deshmukh's photo
Shubham Deshmukh
·Mar 28, 2022·

2 min read

Instrumenting Any Application for Custom metric using Prometheus.

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Today in this blog we will be learning how to add monitoring support to our Go application. Before starting we will learn more about Prometheus.


What is Prometheus ?

Prometheus is an open-source system monitoring and alerting tool. Prometheus collects and stores its metrics as time-series data, i.e. metrics information is stored with the timestamp at which it was recorded, alongside optional key-value pairs called labels. Now we have some idea about what Prometheus is !! Let's start the implementation.


1. Installing Prometheus libraries.

Run the below commands to install Prometheus libraries.

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

2. Writing the Go application.

We will implement Prometheus libraries in our Go code. To expose Prometheus metrics, We need to provide a /metrics HTTP endpoint. We will use promhttp as the handler function. This will expose the metrics at,

localhost:8080/metrics

We have added a custom metric called "my_custom_metric" which will increment its value after every 5 seconds.

package main

import (
        "net/http"
        "time"

        "github.com/prometheus/client_golang/prometheus"
        "github.com/prometheus/client_golang/prometheus/promauto"
        "github.com/prometheus/client_golang/prometheus/promhttp"
)

func recordCustomMetrics() {
        go func() {
                for {
                        mymetric.Inc()
                        time.Sleep(5 * time.Second)
                }
        }()
}

var (
        mymetric = promauto.NewCounter(prometheus.CounterOpts{
                Name: "my_custom_metric",
                Help: "total number for my custom action",
        })
)

func main() {
        recordCustomMetrics()
        http.Handle("/metrics", promhttp.Handler())
        http.ListenAndServe(":8080", nil)
}

3. Running the Application and verifying the metric.

Execute the below command to run the application.

go run main.go

After the application is started we can hit localhost:8080/metrics to check for metrics.

Screenshot 2022-03-25 at 8.14.05 PM.png As we can see the metric is visible in the metrics section.

For more information on Prometheus visit, prometheus.io

Thanks for reading. Hope you have a great day 😁

Did you find this article valuable?

Support Shubham Deshmukh by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this