github.com/lyft/flytestdlib@v0.3.12-0.20210213045714-8cdd111ecda1/promutils/labeled/counter.go (about) 1 package labeled 2 3 import ( 4 "context" 5 6 "github.com/lyft/flytestdlib/contextutils" 7 "github.com/lyft/flytestdlib/promutils" 8 "github.com/prometheus/client_golang/prometheus" 9 ) 10 11 // Represents a counter labeled with values from the context. See labeled.SetMetricsKeys for information about to 12 // configure that. 13 type Counter struct { 14 *prometheus.CounterVec 15 16 prometheus.Counter 17 additionalLabels []contextutils.Key 18 } 19 20 // Inc increments the counter by 1. Use Add to increment it by arbitrary non-negative values. The data point will be 21 // labeled with values from context. See labeled.SetMetricsKeys for information about to configure that. 22 func (c Counter) Inc(ctx context.Context) { 23 counter, err := c.CounterVec.GetMetricWith(contextutils.Values(ctx, append(metricKeys, c.additionalLabels...)...)) 24 if err != nil { 25 panic(err.Error()) 26 } 27 counter.Inc() 28 29 if c.Counter != nil { 30 c.Counter.Inc() 31 } 32 } 33 34 // Add adds the given value to the counter. It panics if the value is < 0.. The data point will be labeled with values 35 // from context. See labeled.SetMetricsKeys for information about to configure that. 36 func (c Counter) Add(ctx context.Context, v float64) { 37 counter, err := c.CounterVec.GetMetricWith(contextutils.Values(ctx, append(metricKeys, c.additionalLabels...)...)) 38 if err != nil { 39 panic(err.Error()) 40 } 41 counter.Add(v) 42 43 if c.Counter != nil { 44 c.Counter.Add(v) 45 } 46 } 47 48 // Creates a new labeled counter. Label keys must be set before instantiating a counter. See labeled.SetMetricsKeys for 49 // information about to configure that. 50 func NewCounter(name, description string, scope promutils.Scope, opts ...MetricOption) Counter { 51 if len(metricKeys) == 0 { 52 panic(ErrNeverSet) 53 } 54 55 c := Counter{} 56 57 for _, opt := range opts { 58 if _, emitUnlabeledMetric := opt.(EmitUnlabeledMetricOption); emitUnlabeledMetric { 59 c.Counter = scope.MustNewCounter(GetUnlabeledMetricName(name), description) 60 } else if additionalLabels, casted := opt.(AdditionalLabelsOption); casted { 61 c.CounterVec = scope.MustNewCounterVec(name, description, append(metricStringKeys, additionalLabels.Labels...)...) 62 c.additionalLabels = contextutils.MetricKeysFromStrings(additionalLabels.Labels) 63 } 64 } 65 66 if c.CounterVec == nil { 67 c.CounterVec = scope.MustNewCounterVec(name, description, metricStringKeys...) 68 } 69 70 return c 71 }