metrics

package
v1.67.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 9 Imported by: 6

README

Package metrics

Пакет metrics предоставляет удобный способ регистрации и экспонирования метрик Prometheus, включая стандартные метрики Go-приложения. Поддерживает кастомную регистрацию метрик, их повторное использование и предоставляет HTTP-обработчики для вывода значений и описаний метрик.

Types

Registry

Структура Registry представляет собой обёртку над prometheus.Registry, обеспечивающую потокобезопасную регистрацию метрик, экспонирование и описание зарегистрированных метрик.

Methods:

func NewRegistry() *Registry

Создаёт новый Registry с предустановленными метриками:

  • go_*
  • process_*
  • build_info
(r *Registry) GetOrRegister(metric Metric) Metric

Регистрирует метрику, если она ещё не была зарегистрирована. В противном случае возвращает уже существующую.

(r *Registry) MetricsHandler() http.Handler

Возвращает HTTP-обработчик (/metrics), совместимый с Prometheus.

(r *Registry) MetricsDescriptionHandler() http.Handler

Возвращает HTTP-обработчик, печатающий описания всех зарегистрированных метрик в текстовом виде. Используется, например, для дебага.

Metric

Интерфейс Metric — это алиас для prometheus.Collector.

func GetOrRegister[M Metric](registry *Registry, metric M) M

Обобщённая функция, упрощающая регистрацию метрик с сохранением типа.

Global variables

var DefaultRegistry = NewRegistry()

Глобальный экземпляр Registry со всеми предустановленными метриками.

var DefaultObjectives map[float64]float64

Типовые квантили для создания Summary-метрик

Functions

func Milliseconds(duration time.Duration) float64

Преобразует time.Duration в миллисекунды как float64. Гарантирует, что 0 миллисекунд будет преобразовано в 1 (чтобы избежать нулевых значений в метриках).

Usage

Default usage flow
import (
    "net/http"

    "github.com/txix-open/isp-kit/metrics"
    "github.com/prometheus/client_golang/prometheus"
)

func main() {
    registry := metrics.NewRegistry()

    http.Handle("/metrics", registry.MetricsHandler())
    http.ListenAndServe(":8080", nil)
}
Registering custom metric
var myCounter = prometheus.NewCounter(prometheus.CounterOpts{
    Name: "my_custom_counter_total",
    Help: "A custom counter example",
})

func main() {
    metrics.DefaultRegistry.GetOrRegister(myCounter).(prometheus.Counter).Inc()
}
Using description handler
http.Handle("/metrics-description", metrics.DefaultRegistry.MetricsDescriptionHandler())

Documentation

Overview

Package metrics provides a Prometheus-based metrics collection system with support for various subsystems including HTTP, gRPC, Kafka, RabbitMQ, SQL, and background jobs.

The package offers a thread-safe registry for managing Prometheus collectors, along with pre-configured storage types for common integration patterns.

Example usage:

reg := metrics.NewRegistry()
httpStorage := http_metrics.NewServerStorage(reg)
http.HandleFunc("/metrics", reg.MetricsHandler())

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultObjectives defines the quantile targets for Prometheus summaries.
	// Each key represents a quantile (e.g., 0.95 for the 95th percentile),
	// and each value represents the allowed error tolerance.
	DefaultObjectives = map[float64]float64{
		0.5:  0.05,
		0.9:  0.01,
		0.95: 0.005,
		0.99: 0.001,
	}
)

nolint:gochecknoglobals,mnd

View Source
var (
	// DefaultRegistry is a globally accessible registry instance for quick access
	// without explicit initialization. Suitable for simple applications or testing.
	DefaultRegistry = NewRegistry()
)

nolint:gochecknoglobals

Functions

func GetOrRegister

func GetOrRegister[M Metric](registry *Registry, metric M) M

GetOrRegister is a generic wrapper around Registry.GetOrRegister that preserves the concrete type of the metric.

func Milliseconds

func Milliseconds(duration time.Duration) float64

Milliseconds converts a time.Duration to milliseconds as a float64. Returns 1 if the duration is zero

Types

type Metric

type Metric interface {
	prometheus.Collector
}

Metric is an alias for Prometheus collector interface.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry provides a thread-safe wrapper around Prometheus registry for managing metric collectors. It automatically registers default Go, build info, and process collectors on creation.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new metric registry with default collectors for Go runtime, build information, and process statistics.

func (*Registry) Gather added in v1.64.3

func (r *Registry) Gather() ([]*io_prometheus_client.MetricFamily, error)

Gather collects all registered metrics and returns them as protobuf-encoded metric families. This method can be used to programmatically access metric data.

func (*Registry) GetOrRegister

func (r *Registry) GetOrRegister(metric Metric) Metric

GetOrRegister attempts to register a metric collector. If the metric is already registered, it returns the existing collector instead. Panics if registration fails for any other reason.

func (*Registry) MetricsDescriptionHandler

func (r *Registry) MetricsDescriptionHandler() http.Handler

MetricsDescriptionHandler returns an HTTP handler that provides human-readable descriptions of all registered metrics. The handler is limited to a 1 second timeout to prevent blocking.

func (*Registry) MetricsHandler

func (r *Registry) MetricsHandler() http.Handler

MetricsHandler returns an HTTP handler that exposes all registered metrics in Prometheus text format. This handler should be mounted on an endpoint (typically "/metrics") for scraping by Prometheus.

func (*Registry) MustRegister added in v1.64.3

func (r *Registry) MustRegister(collectors ...prometheus.Collector)

MustRegister registers multiple collectors. Panics if any collector fails to register.

func (*Registry) Register added in v1.64.3

func (r *Registry) Register(collector prometheus.Collector) error

Register adds a collector to the registry. This is a convenience method that calls GetOrRegister and always returns nil.

func (*Registry) Unregister added in v1.64.3

func (r *Registry) Unregister(collector prometheus.Collector) bool

Unregister removes a collector from the registry. Returns true if the collector was successfully unregistered, false otherwise.

Directories

Path Synopsis
Package app_metrics provides application-level metrics including log sampling statistics.
Package app_metrics provides application-level metrics including log sampling statistics.
Package bgjob_metrics provides Prometheus metric collectors for background job processing.
Package bgjob_metrics provides Prometheus metric collectors for background job processing.
Package db_metrics provides utilities for registering database connection pool metrics.
Package db_metrics provides utilities for registering database connection pool metrics.
Package grpc_metrics provides Prometheus metric collectors for gRPC server and client operations.
Package grpc_metrics provides Prometheus metric collectors for gRPC server and client operations.
Package http_metrics provides Prometheus metric collectors for HTTP server and client operations.
Package http_metrics provides Prometheus metric collectors for HTTP server and client operations.
Package kafka_metrics provides Prometheus metric collectors for Kafka producer and consumer operations.
Package kafka_metrics provides Prometheus metric collectors for Kafka producer and consumer operations.
Package rabbitmq_metrics provides Prometheus metric collectors for RabbitMQ publisher and consumer operations.
Package rabbitmq_metrics provides Prometheus metric collectors for RabbitMQ publisher and consumer operations.
Package sql_metrics provides Prometheus metric collectors for SQL query execution.
Package sql_metrics provides Prometheus metric collectors for SQL query execution.

Jump to

Keyboard shortcuts

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