echoprometheus

package
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 15 Imported by: 60

README

Usage

package main

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo-contrib/echoprometheus"
)

func main() {
    e := echo.New()
    // Enable metrics middleware
    e.Use(echoprometheus.NewMiddleware("myapp"))
    e.GET("/metrics", echoprometheus.NewHandler())

    e.Logger.Fatal(e.Start(":1323"))
}

How to migrate

Creating and adding middleware to the application

Older prometheus middleware

    e := echo.New()
    p := prometheus.NewPrometheus("echo", nil)
    p.Use(e)

With the new echoprometheus middleware

    e := echo.New()
    e.Use(echoprometheus.NewMiddleware("myapp")) // register middleware to gather metrics from requests
    e.GET("/metrics", echoprometheus.NewHandler()) // register route to serve gathered metrics in Prometheus format

Replacement for Prometheus.MetricsList field, NewMetric(m *Metric, subsystem string) function and prometheus.Metric struct

The NewMetric function allowed to create custom metrics with the old prometheus middleware. This helper is no longer available to avoid the added complexity. It is recommended to use native Prometheus metrics and register those yourself.

This can be done now as follows:

	e := echo.New()

	customRegistry := prometheus.NewRegistry() // create custom registry for your custom metrics
	customCounter := prometheus.NewCounter( // create new counter metric. This is replacement for `prometheus.Metric` struct
		prometheus.CounterOpts{
			Name: "custom_requests_total",
			Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
		},
	)
	if err := customRegistry.Register(customCounter); err != nil { // register your new counter metric with metrics registry
		log.Fatal(err)
	}

	e.Use(NewMiddlewareWithConfig(MiddlewareConfig{
		AfterNext: func(c echo.Context, err error) {
			customCounter.Inc() // use our custom metric in middleware. after every request increment the counter
		},
		Registerer: customRegistry, // use our custom registry instead of default Prometheus registry
	}))
	e.GET("/metrics", NewHandlerWithConfig(HandlerConfig{Gatherer: customRegistry})) // register route for getting gathered metrics data from our custom Registry

Replacement for Prometheus.MetricsPath

MetricsPath was used to skip metrics own route from Prometheus metrics. Skipping is no longer done and requests to Prometheus route will be included in gathered metrics.

To restore the old behaviour the /metrics path needs to be excluded from counting using the Skipper function:

conf := echoprometheus.MiddlewareConfig{
    Skipper: func(c echo.Context) bool {
        return c.Path() == "/metrics"
    },
}
e.Use(echoprometheus.NewMiddlewareWithConfig(conf))

Replacement for Prometheus.RequestCounterURLLabelMappingFunc and Prometheus.RequestCounterHostLabelMappingFunc

These function fields were used to define how "URL" or "Host" attribute in Prometheus metric lines are created.

These can now be substituted by using LabelFuncs:

	e.Use(echoprometheus.NewMiddlewareWithConfig(echoprometheus.MiddlewareConfig{
		LabelFuncs: map[string]echoprometheus.LabelValueFunc{
			"scheme": func(c echo.Context, err error) string { // additional custom label
				return c.Scheme()
			},
			"url": func(c echo.Context, err error) string { // overrides default 'url' label value
				return "x_" + c.Request().URL.Path
			},
			"host": func(c echo.Context, err error) string { // overrides default 'host' label value
				return "y_" + c.Request().Host
			},
		},
	}))

Will produce Prometheus line as echo_request_duration_seconds_count{code="200",host="y_example.com",method="GET",scheme="http",url="x_/ok",scheme="http"} 1

Replacement for Metric.Buckets and modifying default metrics

The echoprometheus middleware registers the following metrics by default:

  • Counter requests_total
  • Histogram request_duration_seconds
  • Histogram response_size_bytes
  • Histogram request_size_bytes

You can modify their definition before these metrics are registed with CounterOptsFunc and HistogramOptsFunc callbacks

Example:

	e.Use(NewMiddlewareWithConfig(MiddlewareConfig{
		HistogramOptsFunc: func(opts prometheus.HistogramOpts) prometheus.HistogramOpts {
			if opts.Name == "request_duration_seconds" {
                opts.Buckets = []float64{1.0 * bKB, 2.0 * bKB, 5.0 * bKB, 10.0 * bKB, 100 * bKB, 500 * bKB, 1.0 * bMB, 2.5 * bMB, 5.0 * bMB, 10.0 * bMB}
			}
			return opts
		},
        CounterOptsFunc: func(opts prometheus.CounterOpts) prometheus.CounterOpts {
            if opts.Name == "requests_total" {
                opts.ConstLabels = prometheus.Labels{"my_const": "123"}
            }
            return opts
        },
	}))

Function RunPushGatewayGatherer starts pushing collected metrics and block until context completes or ErrorHandler returns an error. This function should be run in separate goroutine.

Example:

	go func() {
		config := echoprometheus.PushGatewayConfig{
			PushGatewayURL: "https://host:9080",
			PushInterval:   10 * time.Millisecond,
		}
		if err := echoprometheus.RunPushGatewayGatherer(context.Background(), config); !errors.Is(err, context.Canceled) {
			log.Fatal(err)
		}
	}()

Documentation

Overview

Package echoprometheus provides middleware to add Prometheus metrics.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewHandler

func NewHandler() echo.HandlerFunc

NewHandler creates new instance of Handler using Prometheus default registry.

func NewHandlerWithConfig

func NewHandlerWithConfig(config HandlerConfig) echo.HandlerFunc

NewHandlerWithConfig creates new instance of Handler using given configuration.

func NewMiddleware

func NewMiddleware(subsystem string) echo.MiddlewareFunc

NewMiddleware creates new instance of middleware using Prometheus default registry.

func NewMiddlewareWithConfig

func NewMiddlewareWithConfig(config MiddlewareConfig) echo.MiddlewareFunc

NewMiddlewareWithConfig creates new instance of middleware using given configuration.

func RunPushGatewayGatherer

func RunPushGatewayGatherer(ctx context.Context, config PushGatewayConfig) error

RunPushGatewayGatherer starts pushing collected metrics and waits for it context to complete or ErrorHandler to return error.

Example: ```

go func() {
	config := echoprometheus.PushGatewayConfig{
		PushGatewayURL: "https://host:9080",
		PushInterval:   10 * time.Millisecond,
	}
	if err := echoprometheus.RunPushGatewayGatherer(context.Background(), config); !errors.Is(err, context.Canceled) {
		log.Fatal(err)
	}
}()

```

func WriteGatheredMetrics

func WriteGatheredMetrics(writer io.Writer, gatherer prometheus.Gatherer) error

WriteGatheredMetrics gathers collected metrics and writes them to given writer

Types

type HandlerConfig

type HandlerConfig struct {
	// Gatherer sets the prometheus.Gatherer instance the middleware will use when generating the metric endpoint handler.
	// Defaults to: prometheus.DefaultGatherer
	Gatherer prometheus.Gatherer
}

HandlerConfig contains the configuration for creating HTTP handler for metrics.

type LabelValueFunc

type LabelValueFunc func(c echo.Context, err error) string

type MiddlewareConfig

type MiddlewareConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper

	// Namespace is components of the fully-qualified name of the Metric (created by joining Namespace,Subsystem and Name components with "_")
	// Optional
	Namespace string

	// Subsystem is components of the fully-qualified name of the Metric (created by joining Namespace,Subsystem and Name components with "_")
	// Defaults to: "echo"
	Subsystem string

	// LabelFuncs allows adding custom labels in addition to default labels. When key has same name with default label
	// it replaces default one.
	LabelFuncs map[string]LabelValueFunc

	// HistogramOptsFunc allows to change options for metrics of type histogram before metric is registered to Registerer
	HistogramOptsFunc func(opts prometheus.HistogramOpts) prometheus.HistogramOpts

	// CounterOptsFunc allows to change options for metrics of type counter before metric is registered to Registerer
	CounterOptsFunc func(opts prometheus.CounterOpts) prometheus.CounterOpts

	// Registerer sets the prometheus.Registerer instance the middleware will register these metrics with.
	// Defaults to: prometheus.DefaultRegisterer
	Registerer prometheus.Registerer

	// BeforeNext is callback that is executed before next middleware/handler is called. Useful for case when you have own
	// metrics that need data to be stored for AfterNext.
	BeforeNext func(c echo.Context)

	// AfterNext is callback that is executed after next middleware/handler returns. Useful for case when you have own
	// metrics that need incremented/observed.
	AfterNext func(c echo.Context, err error)

	// If DoNotUseRequestPathFor404 is true, all 404 responses (due to non-matching route) will have the same `url` label and
	// thus won't generate new metrics.
	DoNotUseRequestPathFor404 bool
	// contains filtered or unexported fields
}

MiddlewareConfig contains the configuration for creating prometheus middleware collecting several default metrics.

func (MiddlewareConfig) ToMiddleware

func (conf MiddlewareConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts configuration to middleware or returns an error.

type PushGatewayConfig

type PushGatewayConfig struct {
	// PushGatewayURL is push gateway URL in format http://domain:port
	PushGatewayURL string

	// PushInterval in ticker interval for pushing gathered metrics to the Gateway
	// Defaults to: 1 minute
	PushInterval time.Duration

	// Gatherer sets the prometheus.Gatherer instance the middleware will use when generating the metric endpoint handler.
	// Defaults to: prometheus.DefaultGatherer
	Gatherer prometheus.Gatherer

	// ErrorHandler is function that is called when errors occur. When callback returns error StartPushGateway also returns.
	ErrorHandler func(err error) error

	// ClientTransport specifies the mechanism by which individual HTTP POST requests are made.
	// Defaults to: http.DefaultTransport
	ClientTransport http.RoundTripper
}

PushGatewayConfig contains the configuration for pushing to a Prometheus push gateway.

Jump to

Keyboard shortcuts

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