Skip to content

Commit

Permalink
Stabelize order of labels in statsd/graphite/collectd export
Browse files Browse the repository at this point in the history
Signed-off-by: Andreas Jaggi <andreas.jaggi@waterwave.ch>
  • Loading branch information
x-way committed May 28, 2022
1 parent 26b651f commit af57b0c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 8 additions & 2 deletions internal/exporter/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"io"
"net"
"os"
"sort"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -140,10 +141,15 @@ func (e *Exporter) SetOption(options ...Option) error {
func formatLabels(name string, m map[string]string, ksep, sep, rep string) string {
r := name
if len(m) > 0 {
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
var s []string
for k, v := range m {
for _, k := range keys {
k1 := strings.ReplaceAll(strings.ReplaceAll(k, ksep, rep), sep, rep)
v1 := strings.ReplaceAll(strings.ReplaceAll(v, ksep, rep), sep, rep)
v1 := strings.ReplaceAll(strings.ReplaceAll(m[k], ksep, rep), sep, rep)
s = append(s, fmt.Sprintf("%s%s%s", k1, ksep, v1))
}
return r + sep + strings.Join(s, sep)
Expand Down
9 changes: 9 additions & 0 deletions internal/exporter/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,15 @@ func TestMetricToStatsd(t *testing.T) {
t.Errorf("String didn't match:\n\texpected: %v\n\treceived: %v", expected, r)
}

multiLabelMetric := metrics.NewMetric("bar", "prog", metrics.Gauge, metrics.Int, "c", "a", "b")
d, _ = multiLabelMetric.GetDatum("x","z","y")
datum.SetInt(d, 37, ts)
r = FakeSocketWrite(metricToStatsd, multiLabelMetric)
expected = []string{"prog.bar.a.z.b.y.c.x:37|g"}
if !reflect.DeepEqual(expected, r) {
t.Errorf("String didn't match:\n\texpected: %v\n\treceived: %v", expected, r)
}

timingMetric := metrics.NewMetric("foo", "prog", metrics.Timer, metrics.Int)
d, _ = timingMetric.GetDatum()
datum.SetInt(d, 37, ts)
Expand Down

0 comments on commit af57b0c

Please sign in to comment.