Documentation
¶
Overview ¶
Package monitor provides a lightweight metrics collection SDK for Go applications with Prometheus Remote Write and an optional HTTP pull exporter.
Design goals:
- Minimal overhead and allocations for hot paths
- Thread-safe primitives built with atomic operations
- Bounded memory with TTL and max-series limits for labeled counters
- Consistent Prometheus labels across push and pull
Push-only usage remains the default:
config := monitor.Config{
Namespace: "myapp",
Subsystem: "prod",
ServiceName: "service",
RemoteWriteURL: "http://prometheus:9090/api/v1/write",
RemoteWriteInterval: 15 * time.Second,
}
if err := monitor.Init(config); err != nil {
log.Fatal(err)
}
defer monitor.Shutdown()
monitor.IncrementCounter("requests_total")
monitor.SetLabeledCounter("connections", 42, "type", "websocket")
monitor.ObserveHistogram("response_time", 0.123)
To enable the pull exporter, set PrometheusExporter explicitly:
cfg := monitor.Config{
Namespace: "myapp", Subsystem: "prod", ServiceName: "api",
RemoteWriteURL: "http://prometheus:9090/api/v1/write",
RemoteWriteInterval: 15 * time.Second,
PrometheusExporter: &monitor.PrometheusExporterConfig{
ListenAddress: ":9091",
Path: "/metrics",
},
}
Push and pull may run together, but must not deliver to the same logical backend: the SDK does not deduplicate or transactionally coordinate them.
Index ¶
- Variables
- func AddCounter(name string, delta int64)
- func DecrementCounter(name string)
- func DecrementLabeledCounter(name string, labels ...string)
- func DeleteLabeledCounter(name string, labels ...string)
- func ForceWrite() error
- func GetCounter(name string) int64
- func GetLabeledCounter(name string, labels ...string) int64
- func GetOutboundIPv4() (string, error)
- func GetProcessMemory() (alloc, sys, heapInUse uint64)
- func GetStatus() map[string]interface{}
- func HealthCheck() error
- func IncrementCounter(name string)
- func IncrementLabeledCounter(name string, labels ...string)
- func Init(config Config) error
- func ObserveHistogram(name string, value float64)
- func RefreshConnection() error
- func RegisterCollector(collector Collector) error
- func RegisterHistogramBuckets(name string, buckets []float64)
- func RegisterSystemMetricsCollector(logger *zap.Logger) error
- func SetCounter(name string, value int64)
- func SetLabeledCounter(name string, value float64, labels ...string)
- func Shutdown()
- func TriggerGC()
- func TryAddCounter(name string, delta int64) error
- func TryDecrementLabeledCounter(name string, labels ...string) error
- func TryIncrementLabeledCounter(name string, labels ...string) error
- func TrySetLabeledCounter(name string, value float64, labels ...string) error
- type BaseCollector
- type CheckedCollectorRegistrar
- type Collector
- type Config
- type CounterCollector
- func (c *CounterCollector) Add(name string, delta int64)
- func (c *CounterCollector) Collect() []Metric
- func (c *CounterCollector) CollectTo(app SnapshotAppender) error
- func (c *CounterCollector) Get(name string) int64
- func (c *CounterCollector) Inc(name string)
- func (c *CounterCollector) Set(name string, value int64)
- type GCStats
- type HistogramCollector
- type LabeledCounterCollector
- func (c *LabeledCounterCollector) Collect() []Metric
- func (c *LabeledCounterCollector) CollectTo(app SnapshotAppender) error
- func (c *LabeledCounterCollector) Dec(metricName string, labels ...string)
- func (c *LabeledCounterCollector) Delete(metricName string, labels ...string)
- func (c *LabeledCounterCollector) ForceCleanup()
- func (c *LabeledCounterCollector) Get(metricName string, labels ...string) int64
- func (c *LabeledCounterCollector) Inc(metricName string, labels ...string)
- func (c *LabeledCounterCollector) Set(metricName string, value float64, labels ...string)
- func (c *LabeledCounterCollector) SetMaxSeries(n int)
- func (c *LabeledCounterCollector) SetTTL(ttl time.Duration)
- type Manager
- type Metric
- type MetricType
- type PrometheusExporterConfig
- type SnapshotAppender
- type SnapshotCollector
- type SnapshotLabel
- type SystemMetricsCollector
Constants ¶
This section is empty.
Variables ¶
var ( ErrSeriesLimit = errors.New("monitor series limit reached") ErrCollectorLimiterConflict = errors.New("monitor collector already attached to a different series limiter") ErrManagerStopped = errors.New("monitor manager stopped") )
var ( ErrDuplicateSeries = errors.New("duplicate metric series") ErrMetricTypeConflict = errors.New("metric family type conflict") ErrUnsupportedSummary = errors.New("summary requires structured collector") ErrMalformedHistogram = errors.New("malformed legacy histogram") ErrSnapshotLimit = errors.New("snapshot byte limit reached") ErrSnapshotFinished = errors.New("snapshot builder already finished") )
var ( ErrInvalidMetricName = errors.New("invalid prometheus metric name") ErrInvalidLabels = errors.New("invalid prometheus labels") ErrLabelConflict = errors.New("prometheus label conflict") ErrReservedMetricName = errors.New("reserved monitor metric name") ErrNonMonotonicCounter = errors.New("non-monotonic counter operation") )
var ErrRemoteWriteBusy = errors.New("remote write already in progress")
ErrRemoteWriteBusy reports that another Remote Write attempt is active.
var (
ErrRetiredPayloadBusy = errors.New("retired exporter payload is still in use")
)
Functions ¶
func AddCounter ¶
AddCounter adds a specific value to a counter
func DecrementCounter ¶
func DecrementCounter(name string)
DecrementCounter decrements a counter by 1
func DecrementLabeledCounter ¶
DecrementLabeledCounter decrements a labeled counter
func DeleteLabeledCounter ¶
DeleteLabeledCounter deletes a specific labeled counter
func ForceWrite ¶
func ForceWrite() error
ForceWrite immediately writes all current metrics to the remote endpoint This is useful for health checks and testing Concurrent calls return ErrRemoteWriteBusy without starting snapshot or network work.
func GetLabeledCounter ¶
GetLabeledCounter gets the current value of a labeled counter
func GetOutboundIPv4 ¶
GetOutboundIPv4 gets the outbound IPv4 address of the local machine
func GetProcessMemory ¶
func GetProcessMemory() (alloc, sys, heapInUse uint64)
GetProcessMemory returns current process memory usage
func GetStatus ¶
func GetStatus() map[string]interface{}
GetStatus returns the current status of the monitoring system
func HealthCheck ¶
func HealthCheck() error
HealthCheck performs a health check on the monitoring system
func IncrementCounter ¶
func IncrementCounter(name string)
IncrementCounter increments a counter by 1
func IncrementLabeledCounter ¶
IncrementLabeledCounter increments a labeled counter labels should be provided as [key1, value1, key2, value2, ...]
func ObserveHistogram ¶
ObserveHistogram records a value in a histogram
func RefreshConnection ¶
func RefreshConnection() error
RefreshConnection attempts to refresh the remote write connection This is useful for DNS changes or network connectivity issues
func RegisterCollector ¶
RegisterCollector registers a custom metrics collector
func RegisterHistogramBuckets ¶
RegisterHistogramBuckets registers custom histogram buckets
func RegisterSystemMetricsCollector ¶
RegisterSystemMetricsCollector registers the system metrics collector with the global monitor
func SetCounter ¶
SetCounter sets a counter to a specific value
func SetLabeledCounter ¶
SetLabeledCounter sets a labeled counter to a specific value
func TryAddCounter ¶ added in v0.2.0
TryAddCounter adds a non-negative value to a counter and returns validation errors.
func TryDecrementLabeledCounter ¶ added in v0.2.0
TryDecrementLabeledCounter rejects a non-monotonic labeled-counter operation.
func TryIncrementLabeledCounter ¶ added in v0.2.0
TryIncrementLabeledCounter increments a labeled counter and returns validation errors.
Types ¶
type BaseCollector ¶
type BaseCollector struct {
// contains filtered or unexported fields
}
BaseCollector provides basic collector functionality
func NewBaseCollector ¶
func NewBaseCollector(name string, logger *zap.Logger) BaseCollector
NewBaseCollector creates a base collector
func (*BaseCollector) Name ¶
func (b *BaseCollector) Name() string
Name implements Collector interface
type CheckedCollectorRegistrar ¶ added in v0.2.0
CheckedCollectorRegistrar exposes collector registration errors without changing the legacy Manager interface.
type Config ¶
type Config struct {
// Service identification
Namespace string
Subsystem string
ServiceName string
// Remote write configuration
RemoteWriteURL string
RemoteWriteInterval time.Duration
// Instance information
InstanceIP string
Version string
BuildCommit string
BuildTime string
CustomLabels map[string]string
// Optional logger
Logger *zap.Logger
ErrorHandler func(error)
// Optional Prometheus pull exporter configuration
PrometheusExporter *PrometheusExporterConfig
// DNS resolver options (optional, for advanced use cases)
DNSEnable bool
DNSCacheTTL time.Duration
DNSRefreshInterval time.Duration
DNSTimeout time.Duration
DNSUDPServers []string // e.g. ["1.1.1.1:53", "8.8.8.8:53"]
DNSTLSServers []string // e.g. ["1.1.1.1:853", "9.9.9.9:853"]
DNSDoHEndpoints []string // e.g. ["https://cloudflare-dns.com/dns-query"]
}
Config defines the configuration for the metrics system
type CounterCollector ¶
type CounterCollector struct {
BaseCollector
// contains filtered or unexported fields
}
CounterCollector provides simple counter metrics
func NewCounterCollector ¶
func NewCounterCollector(name string, logger *zap.Logger) *CounterCollector
NewCounterCollector creates a new counter collector
func (*CounterCollector) Add ¶
func (c *CounterCollector) Add(name string, delta int64)
Add adds a specific value to a counter
func (*CounterCollector) Collect ¶
func (c *CounterCollector) Collect() []Metric
Collect implements Collector interface
func (*CounterCollector) CollectTo ¶ added in v0.2.0
func (c *CounterCollector) CollectTo(app SnapshotAppender) error
CollectTo appends counter metrics directly to a snapshot.
func (*CounterCollector) Get ¶
func (c *CounterCollector) Get(name string) int64
Get gets the current value of a counter
func (*CounterCollector) Inc ¶
func (c *CounterCollector) Inc(name string)
Inc increments a counter by 1
func (*CounterCollector) Set ¶
func (c *CounterCollector) Set(name string, value int64)
Set sets a counter to a specific value (makes it a gauge)
type HistogramCollector ¶
type HistogramCollector struct {
BaseCollector
// contains filtered or unexported fields
}
HistogramCollector provides histogram metrics.
func NewHistogramCollector ¶
func NewHistogramCollector(name string, logger *zap.Logger) *HistogramCollector
NewHistogramCollector creates a new histogram collector.
func (*HistogramCollector) Collect ¶
func (h *HistogramCollector) Collect() []Metric
Collect implements Collector using the same structured snapshot as CollectTo.
func (*HistogramCollector) CollectTo ¶ added in v0.2.0
func (h *HistogramCollector) CollectTo(app SnapshotAppender) error
CollectTo appends one consistent structured histogram per registered name.
func (*HistogramCollector) Observe ¶
func (h *HistogramCollector) Observe(name string, value float64)
Observe records a value in a histogram.
func (*HistogramCollector) RegisterHistogram ¶
func (h *HistogramCollector) RegisterHistogram(name string, buckets []float64)
RegisterHistogram registers a histogram with specified buckets.
type LabeledCounterCollector ¶
type LabeledCounterCollector struct {
BaseCollector
// contains filtered or unexported fields
}
LabeledCounterCollector provides labeled counter metrics
func NewApplicationCollector ¶
func NewApplicationCollector(name string, logger *zap.Logger) *LabeledCounterCollector
NewApplicationCollector creates an application-specific collector
func NewLabeledCounterCollector ¶
func NewLabeledCounterCollector(name string, logger *zap.Logger) *LabeledCounterCollector
NewLabeledCounterCollector creates a new labeled counter collector
func (*LabeledCounterCollector) Collect ¶
func (c *LabeledCounterCollector) Collect() []Metric
Collect implements Collector interface
func (*LabeledCounterCollector) CollectTo ¶ added in v0.2.0
func (c *LabeledCounterCollector) CollectTo(app SnapshotAppender) error
CollectTo appends labeled metrics directly to a snapshot. Cleanup still runs after an append error, matching the timing of a completed legacy collection.
func (*LabeledCounterCollector) Dec ¶
func (c *LabeledCounterCollector) Dec(metricName string, labels ...string)
Dec decrements a labeled counter
func (*LabeledCounterCollector) Delete ¶
func (c *LabeledCounterCollector) Delete(metricName string, labels ...string)
Delete removes a specific labeled counter entry
func (*LabeledCounterCollector) ForceCleanup ¶
func (c *LabeledCounterCollector) ForceCleanup()
ForceCleanup forces immediate cleanup regardless of time intervals
func (*LabeledCounterCollector) Get ¶
func (c *LabeledCounterCollector) Get(metricName string, labels ...string) int64
Get gets the current value of a labeled counter
func (*LabeledCounterCollector) Inc ¶
func (c *LabeledCounterCollector) Inc(metricName string, labels ...string)
Inc increments a labeled counter
func (*LabeledCounterCollector) Set ¶
func (c *LabeledCounterCollector) Set(metricName string, value float64, labels ...string)
Set sets a labeled counter to a specific value
func (*LabeledCounterCollector) SetMaxSeries ¶
func (c *LabeledCounterCollector) SetMaxSeries(n int)
SetMaxSeries sets the maximum number of time series (0 means no limit)
func (*LabeledCounterCollector) SetTTL ¶
func (c *LabeledCounterCollector) SetTTL(ttl time.Duration)
SetTTL sets the TTL for time series
type Manager ¶
type Manager interface {
Start() error
Stop()
RegisterCollector(collector Collector)
GetMetrics() []Metric
}
Manager is the main interface for metrics collection and reporting
func NewManager ¶
NewManager creates a new metrics manager
type Metric ¶
type Metric struct {
Name string
Value float64
Labels map[string]string
MetricType MetricType
Timestamp time.Time
}
Metric represents a single metric data point
type MetricType ¶
type MetricType int
MetricType represents the type of a metric
const ( Counter MetricType = iota Gauge Histogram Summary )
type PrometheusExporterConfig ¶ added in v0.2.0
type PrometheusExporterConfig struct {
ListenAddress string
Path string
SnapshotCacheTTL time.Duration
MaxConcurrentScrapes int
MaxStoredSeries int
MaxEstimatedStoreBytes int64
MaxSnapshotBytes int64
MaxLabelsPerSeries int
MaxLabelBytesPerSeries int
RemoteWriteBatchSeries int
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
ShutdownTimeout time.Duration
}
PrometheusExporterConfig configures the optional Prometheus pull exporter.
type SnapshotAppender ¶ added in v0.2.0
type SnapshotAppender interface {
AppendScalar(name string, metricType MetricType, value float64, labels []SnapshotLabel) error
AppendHistogram(name string, histogram *dto.Histogram, labels []SnapshotLabel) error
}
SnapshotAppender is valid only for the synchronous duration of a SnapshotCollector.CollectTo call. Collectors must not retain it or use it concurrently.
type SnapshotCollector ¶ added in v0.2.0
type SnapshotCollector interface {
Collector
CollectTo(SnapshotAppender) error
}
type SnapshotLabel ¶ added in v0.2.0
SnapshotLabel is the shared label representation used by validation and later snapshot encoders.
type SystemMetricsCollector ¶
type SystemMetricsCollector struct {
BaseCollector
}
SystemMetricsCollector collects basic system metrics
func NewSystemMetricsCollector ¶
func NewSystemMetricsCollector(logger *zap.Logger) *SystemMetricsCollector
NewSystemMetricsCollector creates a new system metrics collector
func (*SystemMetricsCollector) Collect ¶
func (s *SystemMetricsCollector) Collect() []Metric
Collect implements Collector interface
func (*SystemMetricsCollector) CollectTo ¶ added in v0.2.0
func (s *SystemMetricsCollector) CollectTo(app SnapshotAppender) error
CollectTo appends system metrics directly to a snapshot.