mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Alerting: Better printing of labels (#63348)
This commit changes how labels are printed in templates for custom annotations and labels from map[foo:bar bar:baz] to foo=bar, bar=baz. Labels are comma separated, and sorted in increasing order.
This commit is contained in:
parent
9e86916d48
commit
0659134793
@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"math"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@ -16,10 +17,33 @@ import (
|
||||
"github.com/grafana/grafana/pkg/services/ngalert/eval"
|
||||
)
|
||||
|
||||
type Labels map[string]string
|
||||
|
||||
// String returns the labels as k=v, comma separated, in increasing order.
|
||||
func (l Labels) String() string {
|
||||
// sort the names of the labels in increasing order
|
||||
sorted := make([]string, 0, len(l))
|
||||
for k := range l {
|
||||
sorted = append(sorted, k)
|
||||
}
|
||||
sort.Strings(sorted)
|
||||
// create the string from the sorted labels
|
||||
b := strings.Builder{}
|
||||
for i, k := range sorted {
|
||||
b.WriteString(k)
|
||||
b.WriteString("=")
|
||||
b.WriteString(l[k])
|
||||
if i < len(l)-1 {
|
||||
b.WriteString(", ")
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Value contains the labels and value of a Reduce, Math or Threshold
|
||||
// expression for a series.
|
||||
type Value struct {
|
||||
Labels map[string]string
|
||||
Labels Labels
|
||||
Value float64
|
||||
}
|
||||
|
||||
@ -37,7 +61,7 @@ func NewValues(values map[string]eval.NumberValueCapture) map[string]Value {
|
||||
f = math.NaN()
|
||||
}
|
||||
m[k] = Value{
|
||||
Labels: v.Labels,
|
||||
Labels: Labels(v.Labels),
|
||||
Value: f,
|
||||
}
|
||||
}
|
||||
|
@ -14,6 +14,28 @@ import (
|
||||
"github.com/grafana/grafana/pkg/services/ngalert/eval"
|
||||
)
|
||||
|
||||
func TestLabelsString(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
labels Labels
|
||||
expected string
|
||||
}{{
|
||||
name: "single label has no commas",
|
||||
labels: Labels{"foo": "bar"},
|
||||
expected: "foo=bar",
|
||||
}, {
|
||||
name: "labels are sorted in increasing order",
|
||||
labels: Labels{"foo": "bar", "bar": "baz"},
|
||||
expected: "bar=baz, foo=bar",
|
||||
}}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
assert.Equal(t, test.expected, test.labels.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValueString(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
Loading…
Reference in New Issue
Block a user