monitoring

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-backend-monitoring

Health probes and Prometheus metrics for Go services. Part of the go-backend-* family.

Probes

A Prober runs checks on an interval and keeps the latest result for each one.

State Meaning
loading a required probe has not finished its first run
unstable a required probe failed its last run
stable every required probe passed

Optional probes are reported but never change the overall state.

p := monitoring.NewProber("my-app", monitoring.WithVersion(version))

p.AddProbe("db", func(ctx context.Context) error { return db.PingContext(ctx) })
p.AddServiceProbe("users", "http://users:8080/api/v1")
p.AddTCPProbe("redis", "redis:6379", monitoring.Optional())
p.AddHTTPProbe("website", "https://example.com")
p.AddMetric("queueDepth", func() any { return queue.Len() })

p.Start(ctx)
defer p.Stop()
Probe Default interval / timeout Passes when
AddProbe 30s / 25s the function returns nil
AddServiceProbe 15s / 10s <base>/healthp returns 200 with {"status":"stable"} (any /api... suffix is stripped from the base URL)
AddTCPProbe 15s / 5s a TCP connection opens
AddHTTPProbe 15m / 30s GET returns 2xx or 3xx

Override per probe with Interval(d), Timeout(d) and Optional(). A probe that panics or runs past its timeout counts as failed. Probes don't run on a schedule when the CI environment variable is set (or with WithoutScheduling()); call RunOnce in tests.

Health endpoints

Handler Response
prober.HealthPHandler() always 200, full state: status, instance, version, uptime, goroutines, memory, each probe, custom metrics
prober.ReadinessHandler() 200 when stable, 503 otherwise, {"status": ...}
monitoring.HealthZHandler() always 200, {"status":"OK"}, for liveness checks

/healthp returning 200 even when unstable is deliberate: callers such as AddServiceProbe read the status from the body. Use the readiness handler for load balancers.

Metrics

m := monitoring.NewMetrics(monitoring.MetricsOptions{Module: "my-app"})
mux.Handle("GET /metrics", m.Handler())
handler := m.Middleware(nil)(mux)
Metric Type Labels
http_requests_total counter method
http_requests_path_total counter path
http_request_duration_seconds histogram method, path, status
http_response_duration_ms summary method, path, status
http_active_requests gauge method
http_active_streams gauge stream (closed := m.StreamOpened("events"))

Every metric carries a constant module label. path is the matched http.ServeMux pattern (GET /items/{id}), never the raw URL, so label cardinality stays bounded; unmatched requests are unmatched. /healthp, /healthz and /metrics are not counted. Go runtime and process collectors are included. Register your own collectors with m.MustRegister.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultHTTPClient = &http.Client{Timeout: 30 * time.Second}
View Source
var ErrDuplicateProbe = errors.New("probe already registered")

Functions

func DefaultSkipPaths

func DefaultSkipPaths() map[string]bool

func HealthZHandler

func HealthZHandler() http.Handler

func RecordRoute

func RecordRoute(next http.Handler) http.Handler

func RoutePattern

func RoutePattern(r *http.Request) string

func ServiceHealthURL

func ServiceHealthURL(base string) string

func TrackRoute

func TrackRoute(next http.Handler) http.Handler

Types

type CheckFunc

type CheckFunc func(ctx context.Context) error

func HTTPCheck

func HTTPCheck(client *http.Client, url string) CheckFunc

func ServiceCheck

func ServiceCheck(client *http.Client, base string) CheckFunc

func TCPCheck

func TCPCheck(addr string) CheckFunc

type MemoryState

type MemoryState struct {
	AllocBytes uint64 `json:"allocBytes"`
	SysBytes   uint64 `json:"sysBytes"`
	HeapBytes  uint64 `json:"heapBytes"`
	NumGC      uint32 `json:"numGC"`
}

type MetricFunc

type MetricFunc func() any

type Metrics

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

func NewMetrics

func NewMetrics(o MetricsOptions) *Metrics

func (*Metrics) Handler

func (m *Metrics) Handler() http.Handler

func (*Metrics) Middleware

func (m *Metrics) Middleware(skip map[string]bool) func(http.Handler) http.Handler

func (*Metrics) MustRegister

func (m *Metrics) MustRegister(cs ...prometheus.Collector)

func (*Metrics) Registry

func (m *Metrics) Registry() *prometheus.Registry

func (*Metrics) StreamOpened

func (m *Metrics) StreamOpened(name string) (closed func())

type MetricsOptions

type MetricsOptions struct {
	Module      string
	Buckets     []float64
	ConstLabels prometheus.Labels
	SkipPaths   map[string]bool
}

type ProbeOption

type ProbeOption func(*probe)

func Interval

func Interval(d time.Duration) ProbeOption

func Optional

func Optional() ProbeOption

func Timeout

func Timeout(d time.Duration) ProbeOption

type ProbeState

type ProbeState struct {
	Status      Status    `json:"status"`
	Required    bool      `json:"required"`
	LastRun     time.Time `json:"lastRun,omitzero"`
	DurationMs  int64     `json:"durationMs"`
	Error       string    `json:"error,omitempty"`
	Consecutive int       `json:"consecutiveFailures,omitempty"`
}

type Prober

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

func NewProber

func NewProber(instance string, opts ...ProberOption) *Prober

func (*Prober) AddHTTPProbe

func (p *Prober) AddHTTPProbe(id, url string, opts ...ProbeOption) error

func (*Prober) AddMetric

func (p *Prober) AddMetric(id string, fn MetricFunc)

func (*Prober) AddProbe

func (p *Prober) AddProbe(id string, check CheckFunc, opts ...ProbeOption) error

func (*Prober) AddServiceProbe

func (p *Prober) AddServiceProbe(id, baseURL string, opts ...ProbeOption) error

func (*Prober) AddTCPProbe

func (p *Prober) AddTCPProbe(id, addr string, opts ...ProbeOption) error

func (*Prober) HealthPHandler

func (p *Prober) HealthPHandler() http.Handler

func (*Prober) ReadinessHandler

func (p *Prober) ReadinessHandler() http.Handler

func (*Prober) RunOnce

func (p *Prober) RunOnce(ctx context.Context)

func (*Prober) Start

func (p *Prober) Start(ctx context.Context)

func (*Prober) State

func (p *Prober) State() State

func (*Prober) Status

func (p *Prober) Status() Status

func (*Prober) Stop

func (p *Prober) Stop()

type ProberOption

type ProberOption func(*Prober)

func WithDefaultInterval

func WithDefaultInterval(d time.Duration) ProberOption

func WithDefaultTimeout

func WithDefaultTimeout(d time.Duration) ProberOption

func WithVersion

func WithVersion(v string) ProberOption

func WithoutScheduling

func WithoutScheduling() ProberOption

type State

type State struct {
	Status     Status                `json:"status"`
	Instance   string                `json:"instance"`
	Version    string                `json:"version,omitempty"`
	StartedAt  time.Time             `json:"startedAt"`
	UptimeSec  int64                 `json:"uptimeSeconds"`
	Goroutines int                   `json:"goroutines"`
	Memory     MemoryState           `json:"memory"`
	Probes     map[string]ProbeState `json:"probes"`
	Metrics    map[string]any        `json:"metrics,omitempty"`
}

type Status

type Status string
const (
	StatusLoading  Status = "loading"
	StatusUnstable Status = "unstable"
	StatusStable   Status = "stable"
)

Jump to

Keyboard shortcuts

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