metrics

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2026 License: MIT Imports: 12 Imported by: 0

README

Metrics

A Lightweight and Convenient Library for Prometheus Metrics in Go Services

This library provides ready-to-use tools for collecting and exporting metrics:

  • An HTTP server for the /metrics endpoint
  • Middleware for HTTP requests
  • A unary interceptor for gRPC
  • Monitoring of gRPC connection availability via health checks
  • Convenient wrappers around prometheus/client_golang

Features

  • Fully configurable HTTP metrics server (host, port, timeouts)
  • Automatic collection of HTTP request durations (http_request_duration_seconds)
  • Automatic collection of gRPC request durations (grpc_request_duration_seconds)
  • A Gauge metric for gRPC connection availability (grpc_connection_availability)
  • Helpers for creating Counter, Gauge, Histogram, and Vec metrics
  • Configuration validation and sensible default values
  • Support for a custom prometheus.Registerer

Installation

go get github.com/jwm1rr0rb10/go-metrics 

The library depends on:

  • github.com/prometheus/client_golang
  • github.com/julienschmidt/httprouter
  • google.golang.org/grpc + google.golang.org/grpc/health/grpc_health_v1

After adding the module, execute go mod tidy.


Quick Start

1. Launching the Metrics Server

package main

import (
	"context"
	"log"

	"github.com/jwm1rr0rb10/go-metrics"
)

func main() {
	cfg := metrics.NewConfig(
		metrics.WithHost("0.0.0.0"),
		metrics.WithPort(8081),
		metrics.WithReadTimeout(15*time.Second),
	)

	server, err := metrics.NewServer(cfg)
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		if err := server.Run(ctx); err != nil && err != http.ErrServerClosed {
			log.Printf("Metrics server error: %v", err)
		}
	}()

	log.Printf("Metrics available at http://%s/metrics", cfg.Address()) 
	

	<-ctx.Done() // graceful shutdown
	if err := server.Close(); err != nil {
		log.Printf("Failed to close metrics server: %v", err)
	}
}


2. HTTP Middleware

mux := http.NewServeMux()
mux.HandleFunc("/api/health", healthHandler)

// Wrap the middleware
handler := metrics.RequestDurationMetricHTTPMiddleware(mux)
http.ListenAndServe(":8080", handler)

Metric: http_request_duration_seconds (histogram) with labels method, status_code.


3. gRPC Interceptor

grpcServer := grpc.NewServer(
	grpc.UnaryInterceptor(metrics.RequestDurationMetricUnaryServerInterceptor("auth_service")),
)

Metric: grpc_request_duration_seconds (histogram) with labels service, method, is_error


4. gRPC Connection Monitoring

type myClient struct {
	conn grpc.ClientConnInterface
}

func (c *myClient) Connection() grpc.ClientConnInterface { return c.conn }

monitor := metrics.NewGRPCConnectionMonitor(
	&myClient{conn: externalConn},
	5*time.Second,      // Ping interval
	"my_service",       // from_service
	"payment_service",  // to_service
)

monitor.Start(ctx)

// On shutdown
defer monitor.Close()

Metric: grpc_connection_availability (gauge 0/1) with labels from_service, to_service.


Configuration
cfg := metrics.NewConfig(
	metrics.WithHost("127.0.0.1"),
	metrics.WithPort(9090),
	metrics.WithReadTimeout(30 * time.Second),
	metrics.WithWriteTimeout(30 * time.Second),
	metrics.WithReadHeaderTimeout(5 * time.Second),
)

Default values:

  • host: 0.0.0.0
  • port: 8080
  • read timeout: 10s
  • write timeout: 10s
  • read header timeout: 5s

Validation

cfg.Validate() (called automatically in NewServer).


Custom Metrics

counter := metrics.NewCounter(prometheus.CounterOpts{
	Name: "my_custom_counter",
	Help: "The quantity of something",
})

gaugeVec := metrics.NewGaugeVec(prometheus.GaugeOpts{
	Name: "my_gauge",
	Help: "The meaning of something",
}, []string{"label1", "label2"})

You can change the case:

metrics.SetRegisterer(myCustomRegisterer)

Экспортируемые метрики

Metrics Type Label Description
http_request_duration_seconds Histogram "method, status_code" HTTP Request Duration
grpc_request_duration_seconds Histogram "service, method, is_error" gRPC Request Duration
grpc_connection_availability Gauge "from_service, to_service" gRPC Connection Availability (1/0)

Testing

The repository contains metrics_test.go, which includes tests for config validation and the server lifecycle.


Complete Usage Example

Refer to the tests and the following files: config.go, handler.go, http_middleware.go, grpc_middleware.go, and metrics_grpc_availability.go.


License

MIT License – © Raman Zaitsau @jwm1rrr0rb10


🙌 Contributions

PRs and suggestions welcome! Feel free to fork, open issues, or create a pull request 🚀

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyHost = errors.New("host cannot be empty")
	ErrZeroPort  = errors.New("port cannot be zero")
)
View Source
var (
	// Registerer allows custom metric registration.
	Registerer = prometheus.DefaultRegisterer
)

Functions

func RequestDurationMetricHTTPMiddleware

func RequestDurationMetricHTTPMiddleware(next http.Handler) http.Handler

RequestDurationMetricHTTPMiddleware tracks HTTP request duration and count.

func RequestDurationMetricUnaryServerInterceptor

func RequestDurationMetricUnaryServerInterceptor(serviceName string) grpc.UnaryServerInterceptor

RequestDurationMetricUnaryServerInterceptor tracks gRPC request duration and count.

func SetRegisterer

func SetRegisterer(r prometheus.Registerer)

SetRegisterer sets a custom Prometheus registerer.

Types

type Config

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

Config defines the metrics server configuration.

func NewConfig

func NewConfig(opts ...Option) *Config

NewConfig creates a new Config with defaults and applies options.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid.

type Counter

type Counter = prometheus.Counter

Metric types (aliases from Prometheus).

func NewCounter

func NewCounter(opts CounterOpts) Counter

NewCounter creates a Counter metric.

type CounterOpts

type CounterOpts = prometheus.CounterOpts

Metric types (aliases from Prometheus).

type CounterVec

type CounterVec = prometheus.CounterVec

Metric types (aliases from Prometheus).

func NewCounterVec

func NewCounterVec(opts CounterOpts, labels []string) *CounterVec

NewCounterVec creates a CounterVec metric.

type GRPCConnectionMonitor

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

GRPCConnectionMonitor periodically checks gRPC service health.

func NewGRPCConnectionMonitor

func NewGRPCConnectionMonitor(
	service GRPCService,
	pingTimer time.Duration,
	serviceFrom string,
	serviceTo string,
) *GRPCConnectionMonitor

NewGRPCConnectionMonitor creates a new monitor.

func (*GRPCConnectionMonitor) Close

func (s *GRPCConnectionMonitor) Close() error

Close stops the monitor.

func (*GRPCConnectionMonitor) IsAvailable added in v1.0.2

func (s *GRPCConnectionMonitor) IsAvailable() bool

IsAvailable returns the current connection status.

func (*GRPCConnectionMonitor) Start

func (s *GRPCConnectionMonitor) Start(ctx context.Context)

Start begins health checks.

type GRPCService

type GRPCService interface {
	Connection() grpc.ClientConnInterface
}

GRPCService defines the interface for gRPC connections.

type Gauge

type Gauge = prometheus.Gauge

Metric types (aliases from Prometheus).

func NewGauge

func NewGauge(opts GaugeOpts) Gauge

NewGauge creates a Gauge metric.

type GaugeOpts

type GaugeOpts = prometheus.GaugeOpts

Metric types (aliases from Prometheus).

type GaugeVec

type GaugeVec = prometheus.GaugeVec

Metric types (aliases from Prometheus).

func NewGaugeVec

func NewGaugeVec(opts GaugeOpts, labels []string) *GaugeVec

NewGaugeVec creates a GaugeVec metric.

type Histogram

type Histogram = prometheus.Histogram

Metric types (aliases from Prometheus).

func NewHistogram

func NewHistogram(opts HistogramOpts) Histogram

NewHistogram creates a Histogram metric.

type HistogramOpts

type HistogramOpts = prometheus.HistogramOpts

Metric types (aliases from Prometheus).

type HistogramVec

type HistogramVec = prometheus.HistogramVec

Metric types (aliases from Prometheus).

func NewHistogramVec

func NewHistogramVec(opts HistogramOpts, labels []string) *HistogramVec

NewHistogramVec creates a HistogramVec metric.

type Option

type Option func(*Config)

Option configures the Config.

func WithHost

func WithHost(host string) Option

WithHost sets the server host (default: "0.0.0.0").

func WithPort

func WithPort(port int) Option

WithPort sets the server port (default: 8080).

func WithReadHeaderTimeout

func WithReadHeaderTimeout(timeout time.Duration) Option

WithReadHeaderTimeout sets the read header timeout (default: 5s).

func WithReadTimeout

func WithReadTimeout(timeout time.Duration) Option

WithReadTimeout sets the read timeout (default: 10s).

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) Option

WithWriteTimeout sets the write timeout (default: 10s).

type Server

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

Server runs the metrics HTTP server.

func NewServer

func NewServer(cfg *Config) (*Server, error)

NewServer initializes a new metrics server.

func (*Server) Close

func (s *Server) Close() error

Close forces an immediate shutdown (non-graceful). Prefer canceling the context passed to Run().

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run starts the metrics server and blocks until the context is canceled or the server encounters an error. Uses graceful shutdown on context cancellation.

Jump to

Keyboard shortcuts

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