github.com/influxdata/influxdb/v2@v2.7.6/kit/metric/metrics_options.go (about)

     1  package metric
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/prometheus/client_golang/prometheus"
     8  )
     9  
    10  type (
    11  	// CollectFnOpts provides arguments to the collect operation of a metric.
    12  	CollectFnOpts struct {
    13  		Method          string
    14  		Start           time.Time
    15  		Err             error
    16  		AdditionalProps map[string]interface{}
    17  	}
    18  
    19  	CounterFn func(vec *prometheus.CounterVec, o CollectFnOpts)
    20  
    21  	HistogramFn func(vec *prometheus.HistogramVec, o CollectFnOpts)
    22  
    23  	// VecOpts expands on the
    24  	VecOpts struct {
    25  		Name       string
    26  		Help       string
    27  		LabelNames []string
    28  
    29  		CounterFn   CounterFn
    30  		HistogramFn HistogramFn
    31  	}
    32  )
    33  
    34  type metricOpts struct {
    35  	namespace        string
    36  	service          string
    37  	serviceSuffix    string
    38  	counterMetrics   map[string]VecOpts
    39  	histogramMetrics map[string]VecOpts
    40  }
    41  
    42  func (o metricOpts) serviceName() string {
    43  	if o.serviceSuffix != "" {
    44  		return fmt.Sprintf("%s_%s", o.service, o.serviceSuffix)
    45  	}
    46  	return o.service
    47  }
    48  
    49  // ClientOptFn is an option used by a metric middleware.
    50  type ClientOptFn func(*metricOpts)
    51  
    52  // WithVec sets a new counter vector to be collected.
    53  func WithVec(opts VecOpts) ClientOptFn {
    54  	return func(o *metricOpts) {
    55  		if opts.CounterFn != nil {
    56  			if o.counterMetrics == nil {
    57  				o.counterMetrics = make(map[string]VecOpts)
    58  			}
    59  			o.counterMetrics[opts.Name] = opts
    60  		}
    61  	}
    62  }
    63  
    64  // WithSuffix returns a metric option that applies a suffix to the service name of the metric.
    65  func WithSuffix(suffix string) ClientOptFn {
    66  	return func(opts *metricOpts) {
    67  		opts.serviceSuffix = suffix
    68  	}
    69  }
    70  
    71  func ApplyMetricOpts(opts ...ClientOptFn) *metricOpts {
    72  	o := metricOpts{}
    73  	for _, opt := range opts {
    74  		opt(&o)
    75  	}
    76  	return &o
    77  }
    78  
    79  func (o *metricOpts) ApplySuffix(prefix string) string {
    80  	if o.serviceSuffix != "" {
    81  		return fmt.Sprintf("%s_%s", prefix, o.serviceSuffix)
    82  	}
    83  	return prefix
    84  }