Integrating the Prometheus monitoring system in the Gin framework can help developers collect and display the performance metrics of applications in real-time, facilitating monitoring and troubleshooting.
Prometheus is an open-source monitoring and alerting system, originally developed by SoundCloud and now a graduated project (highest maturity level) of the Cloud Native Computing Foundation (CNCF). It is designed specifically for dynamic cloud-native environments, capable of efficiently collecting, storing, and querying time-series data (i.e., metric data with timestamps), and is widely used in the monitoring of Kubernetes, microservices architectures, and distributed systems.
github.com/prometheus/client_golang/prometheus/promhttp
is a key package in the Prometheus Go client library for exposing monitoring metrics in HTTP services. It provides an HTTP handler that can expose the monitoring metrics of an application in Prometheus format, making it convenient for the Prometheus server to scrape and store these metrics.
Main Functions
- Exposing Monitoring Metrics: By creating an HTTP handler with
promhttp.Handler()
and mounting it to a specific route (such as/metrics
), the monitoring metrics of the application can be exposed in Prometheus format. - Supporting Standard Prometheus Format:
promhttp.Handler
automatically converts the monitoring metrics into Prometheus' text format (Content-Type: text/plain), conforming to Prometheus' scraping specifications. - Performance Optimization:
promhttp.Handler
uses efficient metric collection and serialization logic internally, capable of handling high-concurrency requests.
Basic Usage Example
The following is a complete example of using promhttp.Handler
in the Gin framework:
package mainimport ( "net/http" "time" "github.com/gin-gonic/gin" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp")var ( // Define monitoring metrics httpRequestsTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests", }, []string{"method", "path", "status"}, ) httpRequestDuration = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "Histogram of HTTP request durations", Buckets: []float64{0.1, 0.3, 0.5, 0.7, 1, 2, 5}, }, []string{"method", "path"}, ))func init() { // Register monitoring metrics prometheus.MustRegister(httpRequestsTotal) prometheus.MustRegister(httpRequestDuration)}// PrometheusMiddleware middleware for recording request metricsfunc PrometheusMiddleware() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() path := c.Request.URL.Path method := c.Request.Method c.Next() // Continue processing the request // Record the request processing time and status code duration := time.Since(start).Seconds() status := c.Writer.Status() httpRequestsTotal.WithLabelValues(method, path, strconv.Itoa(status)).Inc() httpRequestDuration.WithLabelValues(method, path).Observe(duration) }}func main() { r := gin.Default() // Use the Prometheus middleware r.Use(PrometheusMiddleware()) // Expose the monitoring metrics endpoint r.GET("/metrics", gin.WrapH(promhttp.Handler())) // Example route r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) // Start the service r.Run(":8080")}
Key Points Explanation
- Registering Metrics: In the
init()
function, useprometheus.MustRegister()
to register the defined monitoring metrics to ensure they can be correctly exposed bypromhttp.Handler
. - Middleware Integration:
PrometheusMiddleware
is a Gin middleware for recording metrics (such as the number of requests and processing time) before and after request processing. - /metrics Endpoint:
r.GET("/metrics", gin.WrapH(promhttp.Handler()))
mountspromhttp.Handler
to the/metrics
route, and the Prometheus server will regularly scrape the data from this endpoint.
Precautions
- Performance Impact:
promhttp.Handler
is lightweight, but in high-concurrency scenarios, it is recommended to avoid frequently callingprometheus.MustRegister()
or dynamically creating metrics. - Security: The
/metrics
endpoint usually does not require authentication, but in a production environment, it is recommended to restrict access permissions through a firewall or reverse proxy (such as Nginx). - Custom Metrics: More metrics (such as Gauge, Summary, etc.) can be defined according to business requirements and updated through middleware or business logic.
With promhttp
, you can easily integrate Prometheus monitoring into any Go HTTP service to achieve comprehensive performance monitoring.