github.com/lyft/flytestdlib@v0.3.12-0.20210213045714-8cdd111ecda1/promutils/labeled/keys.go (about)

     1  package labeled
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"sync"
     7  
     8  	"github.com/lyft/flytestdlib/contextutils"
     9  )
    10  
    11  var (
    12  	ErrAlreadySet = fmt.Errorf("cannot set metric keys more than once")
    13  	ErrEmpty      = fmt.Errorf("cannot set metric keys to an empty set")
    14  	ErrNeverSet   = fmt.Errorf("must call SetMetricKeys prior to using labeled package")
    15  
    16  	// Metric Keys to label metrics with. These keys get pulled from context if they are present. Use contextutils to fill
    17  	// them in.
    18  	metricKeys []contextutils.Key
    19  
    20  	// :(, we have to create a separate list to satisfy the MustNewCounterVec API as it accepts string only
    21  	metricStringKeys []string
    22  	metricKeysAreSet sync.Once
    23  )
    24  
    25  // Sets keys to use with labeled metrics. The values of these keys will be pulled from context at runtime.
    26  func SetMetricKeys(keys ...contextutils.Key) {
    27  	if len(keys) == 0 {
    28  		panic(ErrEmpty)
    29  	}
    30  
    31  	ran := false
    32  	metricKeysAreSet.Do(func() {
    33  		ran = true
    34  		metricKeys = keys
    35  		for _, metricKey := range metricKeys {
    36  			metricStringKeys = append(metricStringKeys, metricKey.String())
    37  		}
    38  	})
    39  
    40  	if !ran && !reflect.DeepEqual(keys, metricKeys) {
    41  		panic(ErrAlreadySet)
    42  	}
    43  }
    44  
    45  func GetUnlabeledMetricName(metricName string) string {
    46  	return metricName + "_unlabeled"
    47  }
    48  
    49  // Warning: This function is not thread safe and should be used for testing only outside of this package.
    50  func UnsetMetricKeys() {
    51  	metricKeys = make([]contextutils.Key, 0)
    52  	metricStringKeys = make([]string, 0)
    53  	metricKeysAreSet = sync.Once{}
    54  }
    55  
    56  func init() {
    57  	UnsetMetricKeys()
    58  }