github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/util/extract/extract.go (about) 1 package extract 2 3 import ( 4 "fmt" 5 6 "github.com/prometheus/common/model" 7 "github.com/prometheus/prometheus/model/labels" 8 9 "github.com/grafana/loki/pkg/logproto" 10 ) 11 12 var errNoMetricNameLabel = fmt.Errorf("No metric name label") 13 14 // MetricNameMatcherFromMatchers extracts the metric name from a set of matchers 15 func MetricNameMatcherFromMatchers(matchers []*labels.Matcher) (*labels.Matcher, []*labels.Matcher, bool) { 16 // Handle the case where there is no metric name and all matchers have been 17 // filtered out e.g. {foo=""}. 18 if len(matchers) == 0 { 19 return nil, matchers, false 20 } 21 22 outMatchers := make([]*labels.Matcher, len(matchers)-1) 23 for i, matcher := range matchers { 24 if matcher.Name != model.MetricNameLabel { 25 continue 26 } 27 28 // Copy other matchers, excluding the found metric name matcher 29 copy(outMatchers, matchers[:i]) 30 copy(outMatchers[i:], matchers[i+1:]) 31 return matcher, outMatchers, true 32 } 33 // Return all matchers if none are metric name matchers 34 return nil, matchers, false 35 } 36 37 // UnsafeMetricNameFromLabelAdapters extracts the metric name from a list of LabelPairs. 38 // The returned metric name string is a reference to the label value (no copy). 39 func UnsafeMetricNameFromLabelAdapters(labels []logproto.LabelAdapter) (string, error) { 40 for _, label := range labels { 41 if label.Name == model.MetricNameLabel { 42 return label.Value, nil 43 } 44 } 45 return "", errNoMetricNameLabel 46 }