mirror of
https://github.com/safing/portbase
synced 2025-09-01 10:09:50 +00:00
Add fetching counter metric type
This commit is contained in:
parent
370609c091
commit
a509febd48
1 changed files with 57 additions and 0 deletions
57
metrics/metric_counter_fetching.go
Normal file
57
metrics/metric_counter_fetching.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
package metrics
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
vm "github.com/VictoriaMetrics/metrics"
|
||||
)
|
||||
|
||||
// FetchingCounter is a counter metric that fetches the values via a function call.
|
||||
type FetchingCounter struct {
|
||||
*metricBase
|
||||
counter *vm.Counter
|
||||
fetchCnt func() uint64
|
||||
}
|
||||
|
||||
// NewFetchingCounter registers a new fetching counter metric.
|
||||
func NewFetchingCounter(id string, labels map[string]string, fn func() uint64, opts *Options) (*FetchingCounter, error) {
|
||||
// Check if a fetch function is provided.
|
||||
if fn == nil {
|
||||
return nil, fmt.Errorf("%w: no fetch function provided", ErrInvalidOptions)
|
||||
}
|
||||
|
||||
// Ensure that there are options.
|
||||
if opts == nil {
|
||||
opts = &Options{}
|
||||
}
|
||||
|
||||
// Make base.
|
||||
base, err := newMetricBase(id, labels, *opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create metric struct.
|
||||
m := &FetchingCounter{
|
||||
metricBase: base,
|
||||
fetchCnt: fn,
|
||||
}
|
||||
|
||||
// Create metric in set
|
||||
m.counter = m.set.NewCounter(m.LabeledID())
|
||||
|
||||
// Register metric.
|
||||
err = register(m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// WritePrometheus writes the metric in the prometheus format to the given writer.
|
||||
func (fc *FetchingCounter) WritePrometheus(w io.Writer) {
|
||||
fc.counter.Set(fc.fetchCnt())
|
||||
fc.metricBase.set.WritePrometheus(w)
|
||||
}
|
Loading…
Add table
Reference in a new issue