metrics

package
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Example (RealWorldUsage)
package main

import (
	"fmt"
	"time"

	"github.com/massonsky/buffalo/pkg/metrics"
)

func main() {
	// Initialize metrics collector
	collector := metrics.NewCollector()
	collector.SetLabel("service", "api-gateway")
	collector.SetLabel("version", "1.0.0")

	// Create metrics
	requestCounter := collector.Counter("http_requests_total")
	errorCounter := collector.Counter("http_errors_total")
	activeConnections := collector.Gauge("active_connections")
	requestDuration := collector.Histogram("request_duration_seconds",
		[]float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0})

	// Simulate some activity
	for i := 0; i < 10; i++ {
		// Track request
		requestCounter.Inc()
		activeConnections.Inc()

		// Simulate request processing
		start := time.Now()
		time.Sleep(time.Millisecond * 10)
		duration := time.Since(start).Seconds()
		requestDuration.Observe(duration)

		// Simulate occasional errors
		if i%3 == 0 {
			errorCounter.Inc()
		}

		activeConnections.Dec()
	}

	// Export metrics
	fmt.Println("=== Metrics Summary ===")
	fmt.Printf("Total Requests: %d\n", requestCounter.Get())
	fmt.Printf("Total Errors: %d\n", errorCounter.Get())
	fmt.Printf("Active Connections: %d\n", activeConnections.Get())
	fmt.Printf("Average Duration: %.3f seconds\n", requestDuration.Average())
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Collector

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

Collector collects and manages metrics.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/metrics"
)

func main() {
	// Create a new metrics collector
	collector := metrics.NewCollector()
	collector.SetLabel("service", "buffalo")
	collector.SetLabel("version", "0.1.0")

	// Create and use a counter
	counter := collector.Counter("requests_total")
	counter.Add(100)

	// Create and use a gauge
	gauge := collector.Gauge("active_connections")
	gauge.Set(42)

	fmt.Printf("Requests: %d\n", counter.Get())
	fmt.Printf("Connections: %d\n", gauge.Get())
}
Output:

Requests: 100
Connections: 42

func NewCollector

func NewCollector() *Collector

NewCollector creates a new metrics collector.

func (*Collector) All

func (c *Collector) All() map[string]Metric

All returns all registered metrics.

func (*Collector) Counter

func (c *Collector) Counter(name string) *Counter

Counter returns a counter metric, creating it if necessary.

func (*Collector) Gauge

func (c *Collector) Gauge(name string) *Gauge

Gauge returns a gauge metric, creating it if necessary.

func (*Collector) Get

func (c *Collector) Get(name string) (Metric, error)

Get retrieves a metric by name.

func (*Collector) GetLabels

func (c *Collector) GetLabels() map[string]string

GetLabels returns all global labels.

func (*Collector) GetOrCreate

func (c *Collector) GetOrCreate(name string, factory func() Metric) Metric

GetOrCreate retrieves a metric or creates it if it doesn't exist.

func (*Collector) Histogram

func (c *Collector) Histogram(name string, buckets []float64) *Histogram

Histogram returns a histogram metric, creating it if necessary.

func (*Collector) Register

func (c *Collector) Register(name string, metric Metric) error

Register registers a new metric.

func (*Collector) Reset

func (c *Collector) Reset()

Reset resets all metrics.

func (*Collector) SetLabel

func (c *Collector) SetLabel(key, value string)

SetLabel sets a global label for all metrics.

func (*Collector) Snapshot

func (c *Collector) Snapshot() *Snapshot

Snapshot creates a snapshot of all metrics.

type Counter

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

Counter is a metric that can only increase.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/metrics"
)

func main() {
	counter := metrics.NewCounter("http_requests")

	// Increment by 1
	counter.Inc()

	// Add a specific value
	counter.Add(5)

	fmt.Printf("Total requests: %d\n", counter.Get())
}
Output:

Total requests: 6

func NewCounter

func NewCounter(name string) *Counter

NewCounter creates a new counter metric.

func (*Counter) Add

func (c *Counter) Add(delta int64)

Add adds the given value to the counter.

func (*Counter) Get

func (c *Counter) Get() int64

Get returns the current value.

func (*Counter) Inc

func (c *Counter) Inc()

Inc increments the counter by 1.

func (*Counter) Name

func (c *Counter) Name() string

Name returns the counter name.

func (*Counter) Reset

func (c *Counter) Reset()

Reset resets the counter to zero.

func (*Counter) Type

func (c *Counter) Type() string

Type returns "counter".

func (*Counter) Value

func (c *Counter) Value() interface{}

Value returns the current counter value.

type ExportFormat

type ExportFormat string

ExportFormat represents the format for exporting metrics.

const (
	FormatText       ExportFormat = "text"
	FormatJSON       ExportFormat = "json"
	FormatPrometheus ExportFormat = "prometheus"
)

type Exporter

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

Exporter exports metrics in various formats.

Example (Prometheus)
package main

import (
	"os"

	"github.com/massonsky/buffalo/pkg/metrics"
)

func main() {
	collector := metrics.NewCollector()
	collector.SetLabel("env", "production")

	counter := collector.Counter("http_requests_total")
	counter.Add(1000)

	gauge := collector.Gauge("cpu_usage_percent")
	gauge.Set(75)

	exporter := metrics.NewExporter(collector)
	exporter.Export(metrics.FormatPrometheus, os.Stdout)
}
Example (Text)
package main

import (
	"os"

	"github.com/massonsky/buffalo/pkg/metrics"
)

func main() {
	collector := metrics.NewCollector()
	collector.SetLabel("service", "buffalo")

	counter := collector.Counter("operations_total")
	counter.Add(150)

	exporter := metrics.NewExporter(collector)
	exporter.Export(metrics.FormatText, os.Stdout)
}

func NewExporter

func NewExporter(collector *Collector) *Exporter

NewExporter creates a new metrics exporter.

func (*Exporter) Export

func (e *Exporter) Export(format ExportFormat, writer io.Writer) error

Export exports metrics in the specified format.

func (*Exporter) LogMetrics

func (e *Exporter) LogMetrics()

LogMetrics logs all metrics using the configured logger.

func (*Exporter) WithLogger

func (e *Exporter) WithLogger(log *logger.Logger) *Exporter

WithLogger sets the logger for the exporter.

type Gauge

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

Gauge is a metric that can increase or decrease.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/metrics"
)

func main() {
	gauge := metrics.NewGauge("memory_usage_mb")

	// Set to a specific value
	gauge.Set(512)

	// Increment
	gauge.Inc()

	// Decrement
	gauge.Dec()

	// Add/subtract values
	gauge.Add(100)
	gauge.Sub(50)

	fmt.Printf("Memory usage: %d MB\n", gauge.Get())
}
Output:

Memory usage: 562 MB

func NewGauge

func NewGauge(name string) *Gauge

NewGauge creates a new gauge metric.

func (*Gauge) Add

func (g *Gauge) Add(delta int64)

Add adds the given value to the gauge.

func (*Gauge) Dec

func (g *Gauge) Dec()

Dec decrements the gauge by 1.

func (*Gauge) Get

func (g *Gauge) Get() int64

Get returns the current value.

func (*Gauge) Inc

func (g *Gauge) Inc()

Inc increments the gauge by 1.

func (*Gauge) Name

func (g *Gauge) Name() string

Name returns the gauge name.

func (*Gauge) Reset

func (g *Gauge) Reset()

Reset resets the gauge to zero.

func (*Gauge) Set

func (g *Gauge) Set(value int64)

Set sets the gauge to the given value.

func (*Gauge) Sub

func (g *Gauge) Sub(delta int64)

Sub subtracts the given value from the gauge.

func (*Gauge) Type

func (g *Gauge) Type() string

Type returns "gauge".

func (*Gauge) Value

func (g *Gauge) Value() interface{}

Value returns the current gauge value.

type Histogram

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

Histogram tracks the distribution of values.

Example
package main

import (
	"fmt"

	"github.com/massonsky/buffalo/pkg/metrics"
)

func main() {
	// Define buckets for request duration in seconds
	buckets := []float64{0.1, 0.5, 1.0, 2.0, 5.0}
	histogram := metrics.NewHistogram("request_duration_seconds", buckets)

	// Record observations
	histogram.Observe(0.2)
	histogram.Observe(0.8)
	histogram.Observe(1.5)
	histogram.Observe(3.0)

	fmt.Printf("Count: %d\n", histogram.Count())
	fmt.Printf("Average: %.2f seconds\n", histogram.Average())
}
Output:

Count: 4
Average: 1.38 seconds

func NewHistogram

func NewHistogram(name string, buckets []float64) *Histogram

NewHistogram creates a new histogram metric.

func (*Histogram) Average

func (h *Histogram) Average() float64

Average returns the average of all observations.

func (*Histogram) Count

func (h *Histogram) Count() int64

Count returns the total number of observations.

func (*Histogram) Name

func (h *Histogram) Name() string

Name returns the histogram name.

func (*Histogram) Observe

func (h *Histogram) Observe(value float64)

Observe records a value in the histogram.

func (*Histogram) Reset

func (h *Histogram) Reset()

Reset resets the histogram.

func (*Histogram) Sum

func (h *Histogram) Sum() float64

Sum returns the sum of all observations.

func (*Histogram) Type

func (h *Histogram) Type() string

Type returns "histogram".

func (*Histogram) Value

func (h *Histogram) Value() interface{}

Value returns the histogram data.

type Metric

type Metric interface {
	// Name returns the metric name.
	Name() string

	// Type returns the metric type.
	Type() string

	// Value returns the current value of the metric.
	Value() interface{}

	// Reset resets the metric to its initial state.
	Reset()
}

Metric is the interface for all metrics.

type MetricSnapshot

type MetricSnapshot struct {
	Name  string
	Type  string
	Value interface{}
}

MetricSnapshot represents a snapshot of a metric.

type Snapshot

type Snapshot struct {
	Timestamp time.Time
	Labels    map[string]string
	Metrics   map[string]MetricSnapshot
}

Snapshot creates a snapshot of all metrics.

Jump to

Keyboard shortcuts

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