ginprometheus

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 10 Imported by: 203

README

go-gin-prometheus

Gin Web Framework Prometheus metrics exporter

Installation

$ go get github.com/zsais/go-gin-prometheus

Usage

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/zsais/go-gin-prometheus"
)

func main() {
	r := gin.New()

	// NewWithConfig is the recommended way to initialize the middleware
	p := ginprometheus.NewWithConfig(ginprometheus.Config{
		Subsystem: "gin",
	})
	p.Use(r)

	r.GET("/", func(c *gin.Context) {
		c.JSON(200, "Hello world!")
	})

	r.Run(":29090")
}

See the example.go file

Custom Labels

It is possible to add custom labels to all metrics.

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/zsais/go-gin-prometheus"
)

func main() {
    r := gin.New()

    // NewWithConfig is the recommended way to initialize the middleware
    p := ginprometheus.NewWithConfig(ginprometheus.Config{
        Subsystem: "gin",
        CustomLabels: map[string]string{
            "custom_label": "custom_value",
        },
    })
    p.Use(r)

    r.GET("/", func(c *gin.Context) {
        c.JSON(200, "Hello world!")
    })

    r.Run(":29090")
}

Disabling Request Body Reading

By default, this middleware reads the entire request body to calculate the request size. This can be expensive for large request bodies. You can disable this behavior by setting the DisableBodyReading option to true. When disabled, the middleware will use the ContentLength header to determine the request size.

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/zsais/go-gin-prometheus"
)

func main() {
    r := gin.New()

    // NewWithConfig is the recommended way to initialize the middleware
    p := ginprometheus.NewWithConfig(ginprometheus.Config{
        Subsystem: "gin",
        DisableBodyReading: true,
    })
    p.Use(r)

    r.GET("/", func(c *gin.Context) {
        c.JSON(200, "Hello world!")
    })

    r.Run(":29090")
}

Preserving a low cardinality for the request counter

The request counter (requests_total) has a url label which, although desirable, can become problematic in cases where your application uses templated routes expecting a great number of variations, as Prometheus explicitly recommends against metrics having high cardinality dimensions:

https://prometheus.io/docs/practices/naming/#labels

If you have for instance a /customer/:name templated route and you don't want to generate a time series for every possible customer name, you could supply this mapping function to the middleware:

package main

import (
	"strings"
	"github.com/gin-gonic/gin"
	"github.com/zsais/go-gin-prometheus"
)

func main() {
	r := gin.New()

	// NewWithConfig is the recommended way to initialize the middleware
	p := ginprometheus.NewWithConfig(ginprometheus.Config{
		Subsystem: "gin",
	})

	p.ReqCntURLLabelMappingFn = func(c *gin.Context) string {
		url := c.Request.URL.Path
		for _, p := range c.Params {
			if p.Key == "name" {
				url = strings.Replace(url, p.Value, ":name", 1)
				break
			}
		}
		return url
	}

	p.Use(r)

	r.GET("/", func(c *gin.Context) {
		c.JSON(200, "Hello world!")
	})

	r.Run(":29090")
}

which would map /customer/alice and /customer/bob to their template /customer/:name, and thus preserve a low cardinality for our metrics.

Note for Contributors

The default branch of this repository will soon be renamed from master to main. To update your local clone after this change has been made, you can use the following commands:

git fetch origin
git checkout main
git branch -u origin/main
git branch -d master

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewMetric

func NewMetric(m *Metric, subsystem string) prometheus.Collector

NewMetric creates a new prometheus collector based on the metric type.

Types

type Config added in v1.0.0

type Config struct {
	// Subsystem is the subsystem name to use for the metrics.
	Subsystem string
	// MetricsList is an optional list of custom metrics to be exposed.
	MetricsList []*Metric
	// CustomLabels is a map of custom labels to be added to all metrics.
	CustomLabels map[string]string
	// DisableBodyReading is a boolean that disables reading the request body.
	DisableBodyReading bool
}

Config is a struct for configuring the Prometheus middleware.

type Metric

type Metric struct {
	// MetricCollector is the prometheus.Collector that will be used to store the
	// metric.
	MetricCollector prometheus.Collector
	// ID is a unique identifier for the metric.
	ID string
	// Name is the name of the metric.
	Name string
	// Description is a short description of the metric.
	Description string
	// Type is the type of the metric. It can be one of the following:
	// counter, counter_vec, gauge, gauge_vec, histogram, histogram_vec, summary,
	// summary_vec.
	Type string
	// Args is a list of labels that can be used to distinguish between different
	// dimensions of the same metric.
	Args []string
}

Metric defines a prometheus metric. It is used to create a new prometheus collector.

type Prometheus

type Prometheus struct {

	// Ppg is the Prometheus Push Gateway configuration.
	Ppg PrometheusPushGateway

	// MetricsList is a list of custom metrics to be exposed.
	MetricsList []*Metric
	// MetricsPath is the path where the metrics will be exposed.
	MetricsPath string

	// ReqCntURLLabelMappingFn is a function that can be used to map the URL
	// to a different label value.
	ReqCntURLLabelMappingFn RequestCounterURLLabelMappingFn

	// URLLabelFromContext is the name of the context key that will be used
	// to get the URL label from the context.
	URLLabelFromContext string
	CustomLabels        map[string]string
	// DisableBodyReading is a boolean that disables reading the request body.
	DisableBodyReading bool
	// contains filtered or unexported fields
}

Prometheus is a middleware that exports Prometheus metrics.

func NewPrometheus

func NewPrometheus(subsystem string, customMetricsList ...[]*Metric) *Prometheus

NewPrometheus creates a new Prometheus middleware for backward compatibility. It's recommended to use NewWithConfig for new projects.

func NewWithConfig added in v1.0.0

func NewWithConfig(cfg Config) *Prometheus

NewWithConfig creates a new Prometheus middleware.

func (*Prometheus) HandlerFunc

func (p *Prometheus) HandlerFunc() gin.HandlerFunc

HandlerFunc returns the gin.HandlerFunc that should be used as a middleware.

func (*Prometheus) SetListenAddress

func (p *Prometheus) SetListenAddress(address string)

SetListenAddress sets the address where the metrics will be exposed.

func (*Prometheus) SetListenAddressWithRouter

func (p *Prometheus) SetListenAddressWithRouter(listenAddress string, r *gin.Engine)

SetListenAddressWithRouter sets the address and a custom router where the metrics will be exposed.

func (*Prometheus) SetMetricsPath

func (p *Prometheus) SetMetricsPath(e *gin.Engine)

SetMetricsPath sets the path where the metrics will be exposed.

func (*Prometheus) SetMetricsPathWithAuth

func (p *Prometheus) SetMetricsPathWithAuth(e *gin.Engine, accounts gin.Accounts)

SetMetricsPathWithAuth sets the path where the metrics will be exposed and protects it with basic authentication.

func (*Prometheus) SetPushGateway

func (p *Prometheus) SetPushGateway(pushGatewayURL, metricsURL string, pushIntervalSeconds time.Duration)

SetPushGateway configures the middleware to push metrics to a Prometheus pushgateway.

pushGatewayURL is the URL of the pushgateway.

metricsURL is the URL where the metrics are exposed.

pushIntervalSeconds is the interval at which metrics will be pushed to the pushgateway.

func (*Prometheus) SetPushGatewayJob

func (p *Prometheus) SetPushGatewayJob(j string)

SetPushGatewayJob sets the job name for the pushgateway.

func (*Prometheus) Use

func (p *Prometheus) Use(e *gin.Engine)

Use adds the middleware to a gin engine.

func (*Prometheus) UseWithAuth

func (p *Prometheus) UseWithAuth(e *gin.Engine, accounts gin.Accounts)

UseWithAuth adds the middleware to a gin engine with basic authentication.

type PrometheusPushGateway

type PrometheusPushGateway struct {

	// PushIntervalSeconds is the interval at which metrics will be pushed to the
	// pushgateway.
	PushIntervalSeconds time.Duration

	// PushGatewayURL is the URL of the pushgateway.
	PushGatewayURL string

	// MetricsURL is the URL where the metrics are exposed.
	MetricsURL string

	// Job is the job name that will be used when pushing to the pushgateway.
	Job string
}

PrometheusPushGateway contains the configuration for pushing to a Prometheus pushgateway.

type RequestCounterURLLabelMappingFn

type RequestCounterURLLabelMappingFn func(c *gin.Context) string

RequestCounterURLLabelMappingFn is a function which can be supplied to the middleware to control the cardinality of the request counter's "url" label, which might be required in some contexts. For instance, if for a "/customer/:name" route you don't want to generate a time series for every possible customer name, you could use this function:

func(c *gin.Context) string {
	url := c.Request.URL.Path
	for _, p := range c.Params {
		if p.Key == "name" {
			url = strings.Replace(url, p.Value, ":name", 1)
			break
		}
	}
	return url
}

which would map "/customer/alice" and "/customer/bob" to their template "/customer/:name".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL