Skip to content

Commit

Permalink
[telemetry] Deterministic attribute ordering
Browse files Browse the repository at this point in the history
Sort telemetry attributes by key, alphabetically.
  • Loading branch information
andreasjansson committed Jul 19, 2024
1 parent 6cbfa70 commit 21f4e8b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
4 changes: 4 additions & 0 deletions telemetry/attributes.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"sort"

"go.opentelemetry.io/otel/attribute"
)
Expand Down Expand Up @@ -55,6 +56,9 @@ func (as *Attributes) UnmarshalJSON(b []byte) error {
}
kvs = append(kvs, attribute.KeyValue{Key: key, Value: value})
}
sort.Slice(kvs, func(i, j int) bool {
return string(kvs[i].Key) < string(kvs[j].Key)
})

*as = kvs

Expand Down
10 changes: 5 additions & 5 deletions telemetry/attributes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,24 @@ var attributeTestCases = []struct {
JSON: `{"age": 42, "zero": 0, "bigger_than_int32": 2147483650}`,
KVs: []attribute.KeyValue{
attribute.Int("age", 42),
attribute.Int("zero", 0),
attribute.Int("bigger_than_int32", 2147483650),
attribute.Int("zero", 0),
},
},
{
Name: "float64",
JSON: `{"pi": 3.141592653589793, "negative": -1.234567}`,
KVs: []attribute.KeyValue{
attribute.Float64("pi", 3.141592653589793),
attribute.Float64("negative", -1.234567),
attribute.Float64("pi", 3.141592653589793),
},
},
{
Name: "string",
JSON: `{"name": "Boz", "empty": ""}`,
KVs: []attribute.KeyValue{
attribute.String("name", "Boz"),
attribute.String("empty", ""),
attribute.String("name", "Boz"),
},
},
{
Expand Down Expand Up @@ -73,8 +73,8 @@ var attributeTestCases = []struct {
Name: "string slice",
JSON: `{"hobbies": ["gardening", "fishing"], "empty": []}`,
KVs: []attribute.KeyValue{
attribute.StringSlice("hobbies", []string{"gardening", "fishing"}),
attribute.StringSlice("empty", []string{}),
attribute.StringSlice("hobbies", []string{"gardening", "fishing"}),
},
},
}
Expand Down Expand Up @@ -123,7 +123,7 @@ func TestAttributesUnmarshal(t *testing.T) {
err := json.Unmarshal([]byte(tc.JSON), &attrs)
require.NoError(t, err)

assert.ElementsMatch(t, tc.KVs, attrs)
assert.Equal(t, Attributes(tc.KVs), attrs)
})
}
}
Expand Down

0 comments on commit 21f4e8b

Please sign in to comment.