github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/obs/metrics_prom.go (about) 1 package obs 2 3 import ( 4 "strings" 5 6 "github.com/prometheus/client_golang/prometheus" 7 ) 8 9 type promMetricReceiver struct { 10 counter prometheus.Counter 11 } 12 13 func (r *promMetricReceiver) Inc() { 14 r.counter.Inc() 15 } 16 17 func (r *promMetricReceiver) Add(delta float64) { 18 r.counter.Add(delta) 19 } 20 21 type promGaugeReceiver struct { 22 gauge prometheus.Gauge 23 } 24 25 func (r *promGaugeReceiver) Set(value float64) { 26 r.gauge.Set(value) 27 } 28 29 func (r *promGaugeReceiver) Add(delta float64) { 30 r.gauge.Add(delta) 31 } 32 33 func (r *promGaugeReceiver) Sub(delta float64) { 34 r.gauge.Sub(delta) 35 } 36 37 type prometheusMetricsProvider struct { 38 namespace string 39 subsystem string 40 } 41 42 type promHistogramReceiver struct { 43 histogram prometheus.Histogram 44 } 45 46 func (r *promHistogramReceiver) Observe(value float64) { 47 r.histogram.Observe(value) 48 } 49 50 // NewPrometheusMetricsProvider creates a new Provider that uses Prometheus 51 // Go SDK to create metrics. 52 func NewPrometheusMetricsProvider(namespace, subsystem string) Provider { 53 return &prometheusMetricsProvider{ 54 namespace: strings.ReplaceAll(namespace, "-", "_"), 55 subsystem: strings.ReplaceAll(subsystem, "-", "_"), 56 } 57 } 58 59 func (p *prometheusMetricsProvider) NewCounter(name, desc string) Counter { 60 c := prometheus.NewCounter(prometheus.CounterOpts{ 61 Namespace: p.namespace, 62 Subsystem: p.subsystem, 63 Name: name, 64 Help: desc, 65 }) 66 67 prometheus.MustRegister(c) 68 return &promMetricReceiver{ 69 counter: c, 70 } 71 } 72 73 func (p *prometheusMetricsProvider) NewGauge(name, desc string) Gauge { 74 g := prometheus.NewGauge(prometheus.GaugeOpts{ 75 Namespace: p.namespace, 76 Subsystem: p.subsystem, 77 Name: name, 78 Help: desc, 79 }) 80 81 prometheus.MustRegister(g) 82 return &promGaugeReceiver{ 83 gauge: g, 84 } 85 } 86 87 func (p *prometheusMetricsProvider) NewHistogram(name, desc string, 88 opts ...ProviderSpecificOptsEditor) Histogram { 89 histogramOpts := prometheus.HistogramOpts{ 90 Namespace: p.namespace, 91 Subsystem: p.subsystem, 92 Name: name, 93 Help: desc, 94 } 95 96 for _, editor := range opts { 97 editor(&histogramOpts) 98 } 99 100 return &promHistogramReceiver{ 101 histogram: prometheus.NewHistogram(histogramOpts), 102 } 103 }