Prometheus Client Integration
The go-metrics
package supports Prometheus client integration for exposing metrics in a Prometheus-compatible format.
Configuration
The Prometheus client integration is enabled by using the prometheus
namespace in the go-metrics
configuration. This namespace provides a Registry
interface that can be used to register metrics with Prometheus.
Example:
import (
"github.com/docker/go-metrics"
"github.com/prometheus/client_golang/prometheus"
)
func main() {
// Create a Prometheus registry.
registry := prometheus.NewRegistry()
// Create a new go-metrics registry with the Prometheus namespace.
metricsRegistry := metrics.NewRegistry(metrics.PrometheusNamespace(registry))
// Register a counter metric.
metricsRegistry.GetOrRegisterCounter("requests", "total number of requests").Inc(1)
// Run the Prometheus server.
http.Handle("/metrics", prometheus.Handler())
http.ListenAndServe(":9090", nil)
}
References:
Metrics Registration
The go-metrics
package provides various methods to register different types of metrics with Prometheus, including:
- Counters: Count occurrences of an event.
- Gauges: Measure a specific value.
- Timers: Measure the duration of an event.
- Histograms: Measure the distribution of values.
To register a metric, use the GetOrRegister
method on the prometheus.Registry
interface, passing in the metric type, name, and help text.
Example:
// Register a counter metric.
metricsRegistry.GetOrRegisterCounter("requests", "total number of requests").Inc(1)
// Register a gauge metric.
metricsRegistry.GetOrRegisterGauge("memory_usage", "current memory usage").Update(100)
// Register a timer metric.
metricsRegistry.GetOrRegisterTimer("request_duration", "duration of requests").Update(time.Second * 2)
// Register a histogram metric.
metricsRegistry.GetOrRegisterHistogram("request_size", "distribution of request sizes").Update(1024)
References:
Metric Naming Conventions
The go-metrics
package follows the Prometheus metric naming conventions:
- Metric names should be lowercase and separated by underscores.
- Metric names should be descriptive.
- Metric labels should be lowercase and separated by underscores.
- Metric labels should be unique within a metric.
References:
Metric Collection
The Prometheus client integration exposes metrics as Prometheus metrics. The prometheus.Registry
interface provides a handler that can be used to serve metrics to Prometheus.
Example:
// Run the Prometheus server.
http.Handle("/metrics", prometheus.Handler())
http.ListenAndServe(":9090", nil)
References:
Metric Access
You can directly access the registered metrics through the prometheus.Registry
interface. For example, you can retrieve a specific metric and update its value.
Example:
// Get the registered counter metric.
counter := metricsRegistry.GetOrRegisterCounter("requests", "total number of requests")
// Increment the counter value.
counter.Inc(1)