metrics.go 1.2 KB
Newer Older
Y
Your Name 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
package graphite

import (
	"strings"
	"unicode"

	"github.com/eolinker/goku-api-gateway/diting"
	"github.com/marpaia/graphite-golang"
)

//Metrics Metrics
type Metrics interface {
	Metrics() []graphite.Metric
}

//MetricKey MetricKey
type MetricKey interface {
	Key(labels diting.Labels, valueType string) string
}

type _MetricKey struct {
	name       string
	labelNames []string
}

//NewMetricKey new MetricKey
func NewMetricKey(name string, labelNames []string) MetricKey {
	return &_MetricKey{name: name, labelNames: labelNames}
}

//Key key
func (m *_MetricKey) Key(labels diting.Labels, valueType string) string {
	tmp := make([]string, 0, len(m.labelNames)+2)
	tmp = append(tmp, m.name)

	for _, name := range m.labelNames {
Y
Your Name 已提交
37
		labelValue := labels[name]
Y
Your Name 已提交
38 39 40 41 42 43 44 45 46
		tmp = append(tmp, formatLabelValue(labelValue))
	}

	if valueType != "" {
		tmp = append(tmp, formatLabelValue(valueType))
	}
	return strings.Join(tmp, ".")
}

Y
Your Name 已提交
47 48
const rep = '_'

Y
Your Name 已提交
49
//formatLabelValue 将label value的所有字母、数字转换成 _
Y
Your Name 已提交
50 51
func formatLabelValue(value string) string {
	s := []rune(value)
Y
Your Name 已提交
52 53 54 55 56 57
	for i, r := range s {
		if !unicode.IsLetter(r) && !unicode.IsNumber(r) {
			s[i] = rep
		}
	}
	return string(s)
Y
Your Name 已提交
58
}