As counter is one of the most basic metric in monitoring, we can add custom Prometheus counter metric into Gin Gonic application.
Let’s start with this simple Gin gonic application:
package main
import (
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
router.GET("/metrics", gin.WrapH(promhttp.Handler()))
router.Run(":8080")
}
Now, we want to add a custom counter metric, let say total number of HTTP request.
First, we create a new counter object, which defines name and help text for the metric.
requestCounter := prometheus.NewCounter(
prometheus.CounterOpts{
Name: "custom_http_request_counter",
Help: "Number of HTTP requests",
})
Next step is to register the counter metric collector into default Prometheus registry.
prometheus.Register(requestCounter)
Last step, we need to determine when to increase the counter value, and we will test that in the default /
route.
router.GET("/", func(context *gin.Context) {
// increase the counter value
requestCounter.Inc()
context.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
All done for the code, execute the code and access the exported Prometheus metric router in the browser, in this case, it is /metrics
, and you will see our custom metric showing on the output.
# HELP http_request_counter Number of HTTP requests
# TYPE http_request_counter counter
http_request_counter 0
To make sure it shows the correct counter value, access the route /
, and visit the /metrics
again, the counter value should be increased.
# HELP http_request_counter Number of HTTP requests
# TYPE http_request_counter counter
http_request_counter 1
Alright, that’s how you add custom Prometheus counter metric into Gin Gonic application.
Have fun!