metrics

package
v1.23.2 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2025 License: MIT Imports: 4 Imported by: 4

Documentation

Overview

Package metrics is the primary entrypoint into LabKit's metrics utilities.

Provided Functionality

- Provides http middlewares for recording metrics for an http server - Provides a collector for sql.DBStats metrics

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HandlerFactory

type HandlerFactory func(next http.Handler, opts ...HandlerOption) http.Handler

HandlerFactory creates handler middleware instances. Created by NewHandlerFactory.

func NewHandlerFactory

func NewHandlerFactory(opts ...HandlerFactoryOption) HandlerFactory

NewHandlerFactory will create a function for creating metric middlewares. The resulting function can be called multiple times to obtain multiple middleware instances. Each instance can be configured with different options that will be applied to the same underlying metrics.

Example
package main

import (
	"fmt"
	"log"
	"net/http"

	"gitlab.com/gitlab-org/labkit/metrics"
)

func main() {
	// Tell prometheus to include a "route" label for the http metrics
	newMetricHandlerFunc := metrics.NewHandlerFactory(metrics.WithLabels("route"))

	http.Handle("/foo",
		newMetricHandlerFunc(
			http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintf(w, "Hello foo")
			}),
			metrics.WithLabelValues(map[string]string{"route": "/foo"}), // Add instrumentation with a custom label of route="/foo"
		))

	http.Handle("/bar",
		newMetricHandlerFunc(
			http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintf(w, "Hello bar")
			}),
			metrics.WithLabelValues(map[string]string{"route": "/bar"}), // Add instrumentation with a custom label of route="/bar"
		))

	log.Fatal(http.ListenAndServe(":8080", nil))
}

type HandlerFactoryOption

type HandlerFactoryOption func(*handlerFactoryConfig)

HandlerFactoryOption is used to pass options in NewHandlerFactory.

func WithByteSizeBuckets

func WithByteSizeBuckets(buckets []float64) HandlerFactoryOption

WithByteSizeBuckets will configure the byte size histogram buckets for request and response payloads.

func WithLabels

func WithLabels(labels ...string) HandlerFactoryOption

WithLabels will configure additional labels to apply to the metrics.

func WithNamespace

func WithNamespace(namespace string) HandlerFactoryOption

WithNamespace will configure the namespace to apply to the metrics.

func WithRequestDurationBuckets

func WithRequestDurationBuckets(buckets []float64) HandlerFactoryOption

WithRequestDurationBuckets will configure the duration buckets used for incoming request histogram buckets.

func WithTimeToWriteHeaderDurationBuckets

func WithTimeToWriteHeaderDurationBuckets(buckets []float64) HandlerFactoryOption

WithTimeToWriteHeaderDurationBuckets will configure the time to write header duration histogram buckets.

type HandlerOption

type HandlerOption func(*handlerConfig)

HandlerOption is used to pass options to the HandlerFactory instance.

func WithLabelFromContext added in v1.22.0

func WithLabelFromContext(name string, valueFn LabelValueFromContext) HandlerOption

WithLabelFromContext will configure labels values to apply to this handler, allowing for dynamic label values to be added to the standard metrics. This is equivalent to promhttp.WithLabelFromCtx

Example

ExampleWithLabelFromContext shows how metrics can be configured to use dynamic labels pulled from the request context.

package main

import (
	"context"
	"fmt"
	"log"
	"math/rand"
	"net/http"

	"gitlab.com/gitlab-org/labkit/metrics"
)

func main() {
	// We'll store a random color in the request context using a custom key.
	type ctxKeyType struct{}
	var colorKey = ctxKeyType{}

	// A simple middleware that assigns a random color and puts it in the request context.
	injectColor := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			color := "blue"
			if rand.Intn(2) == 0 {
				color = "red"
			}
			ctx := context.WithValue(r.Context(), colorKey, color)

			log.Printf("Injected color: %s", color)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}

	// Create a metrics handler factory with a custom "color" label
	newMetricHandlerFunc := metrics.NewHandlerFactory(
		metrics.WithLabels("color"),
	)

	// Define final handler
	finalHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello dynamic color!\n")
	})

	// Wrap final handler with LabKit instrumentation, telling it how to extract
	// "color" from the request context.
	instrumentedHandler := newMetricHandlerFunc(
		finalHandler,
		metrics.WithLabelFromContext("color", func(ctx context.Context) string {
			if c, ok := ctx.Value(colorKey).(string); ok {
				return c
			}
			return "unknown"
		}),
	)

	// Wrap the instrumented handler with injectColor
	http.Handle("/color", injectColor(instrumentedHandler))

	log.Println("Starting server on :8080 for label from context example...")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func WithLabelValues

func WithLabelValues(labelValues map[string]string) HandlerOption

WithLabelValues will configure labels values to apply to this handler.

type LabelValueFromContext added in v1.22.0

type LabelValueFromContext func(ctx context.Context) string

LabelValueFromContext is used to compute the label value from request context. Context can be filled with values from request through middleware. This matches promhttp.LabelValueFromCtx

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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