metrics

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 14 Imported by: 2

Documentation

Overview

Package metrics provides a reusable, library-friendly wrapper around the OpenTelemetry Go metrics SDK with a Prometheus exporter.

It handles the boilerplate of constructing a MeterProvider with a Prometheus exporter, a Resource describing the service, and custom histogram bucket boundaries — while exposing the full OpenTelemetry metric API (Counter, Histogram, Gauge, UpDownCounter) for application code.

A Prometheus-compatible HTTP handler is provided for the /metrics endpoint.

Quick start

provider, err := metrics.Init(metrics.Config{
    ServiceName:    "my-service",
    ServiceVersion: "1.0.0",
})
if err != nil {
    log.Fatal(err)
}
defer provider.Shutdown(ctx)

// Register the /metrics endpoint.
http.Handle("/metrics", provider.HTTPHandler())
go http.ListenAndServe(":9090", nil)

// Create and use instruments.
counter, _ := provider.Meter().Float64Counter("requests_total",
    metric.WithDescription("Total number of requests"))
counter.Add(ctx, 1)

Index

Constants

This section is empty.

Variables

View Source
var DefaultHTTPBuckets = []float64{
	0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10,
}

DefaultHTTPBuckets are the default histogram buckets for HTTP request duration (in seconds).

Functions

func Float64Counter

func Float64Counter(name string, opts ...otelmetric.Float64CounterOption) (otelmetric.Float64Counter, error)

Float64Counter creates a float64 counter using the global MeterProvider.

func Float64Histogram

func Float64Histogram(name string, opts ...otelmetric.Float64HistogramOption) (otelmetric.Float64Histogram, error)

Float64Histogram creates a float64 histogram using the global MeterProvider.

func Float64ObservableGauge

Float64ObservableGauge creates a float64 observable gauge using the global MeterProvider.

func Float64UpDownCounter

Float64UpDownCounter creates a float64 up-down counter using the global MeterProvider.

func Int64Counter

func Int64Counter(name string, opts ...otelmetric.Int64CounterOption) (otelmetric.Int64Counter, error)

Int64Counter creates an int64 counter using the global MeterProvider.

func Int64Histogram

func Int64Histogram(name string, opts ...otelmetric.Int64HistogramOption) (otelmetric.Int64Histogram, error)

Int64Histogram creates an int64 histogram using the global MeterProvider.

func Int64ObservableGauge

Int64ObservableGauge creates an int64 observable gauge using the global MeterProvider.

func Int64UpDownCounter

func Int64UpDownCounter(name string, opts ...otelmetric.Int64UpDownCounterOption) (otelmetric.Int64UpDownCounter, error)

Int64UpDownCounter creates an int64 up-down counter using the global MeterProvider.

func KeyBool

func KeyBool(key string, value bool) attribute.KeyValue

KeyBool creates an attribute.KeyValue from a string key and bool value.

func KeyFloat

func KeyFloat(key string, value float64) attribute.KeyValue

KeyFloat creates an attribute.KeyValue from a string key and float64 value.

func KeyInt

func KeyInt(key string, value int) attribute.KeyValue

KeyInt creates an attribute.KeyValue from a string key and int value.

func KeyValue

func KeyValue(key, value string) attribute.KeyValue

KeyValue creates an attribute.KeyValue from a string key and string value. This is a convenience helper for common metric attribute usage.

Types

type Config

type Config struct {
	// ServiceName identifies the emitting service. Required.
	ServiceName string
	// ServiceVersion is the service version. Optional.
	ServiceVersion string
	// ServiceNamespace groups services under a namespace. Optional.
	ServiceNamespace string
	// Environment is the deployment environment. Optional.
	Environment string
	// ResourceAttributes are additional key-value attributes attached to the
	// resource.
	ResourceAttributes map[string]string
	// DefaultHistogramBuckets sets the default bucket boundaries for ALL
	// histograms that don't specify their own. If empty, the OpenTelemetry
	// default buckets are used.
	DefaultHistogramBuckets []float64
	// SetGlobal registers the provider as the global MeterProvider. Default: true.
	SetGlobal bool
	// PrometheusRegistry is the Prometheus registry to use. If nil, a new
	// private registry is created (not the global default).
	PrometheusRegistry promclient.Registerer
	// PrometheusGatherer is the Prometheus gatherer to use. If nil, a new
	// private gatherer is created.
	PrometheusGatherer promclient.Gatherer
}

Config configures the metrics provider.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

type HTTPMiddleware

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

HTTPMiddleware is an HTTP middleware that records request duration and count metrics. It uses the provider's meter to create the instruments.

func NewHTTPMiddleware

func NewHTTPMiddleware(p *Provider) (*HTTPMiddleware, error)

NewHTTPMiddleware creates an HTTP metrics middleware.

func (*HTTPMiddleware) Wrap

func (m *HTTPMiddleware) Wrap(next http.Handler) http.Handler

Wrap wraps an http.Handler with metrics instrumentation. The following attributes are recorded on both instruments:

  • method: HTTP method (GET, POST, ...)
  • status: HTTP status code as a string (e.g. "200", "404")
  • path: request URL path

type Provider

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

Provider wraps an SDK MeterProvider with its Prometheus exporter and HTTP handler.

func Init

func Init(cfg Config) (*Provider, error)

Init creates a metrics Provider from the given Config, registers it globally (if SetGlobal is true), and returns the provider.

Call Shutdown on the returned provider on application exit.

func NewProvider

func NewProvider(cfg Config) (*Provider, error)

NewProvider creates a metrics Provider without setting globals.

func (*Provider) Exporter

func (p *Provider) Exporter() *otelprom.Exporter

Exporter returns the underlying Prometheus exporter.

func (*Provider) HTTPHandler

func (p *Provider) HTTPHandler() http.Handler

HTTPHandler returns an http.Handler that exposes the Prometheus metrics. Use it with http.Handle("/metrics", provider.HTTPHandler()).

func (*Provider) Meter

func (p *Provider) Meter() otelmetric.Meter

Meter returns a meter with the configured service name.

func (*Provider) MeterProvider

func (p *Provider) MeterProvider() *metric.MeterProvider

MeterProvider returns the underlying SDK MeterProvider.

func (*Provider) Shutdown

func (p *Provider) Shutdown(ctx context.Context) error

Shutdown flushes and shuts down the provider. It is safe to call multiple times.

Jump to

Keyboard shortcuts

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