Skip to content

Commit

Permalink
supports marshaling values as json (#948)
Browse files Browse the repository at this point in the history
  • Loading branch information
lizthegrey authored Jul 17, 2020
1 parent d6ad4d4 commit b2b23e1
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

- Github action to generate protobuf Go bindings locally in `internal/opentelemetry-proto-gen`. (#938)
- OTLP .proto files from `open-telemetry/opentelemetry-proto` imported as a git submodule under `internal/opentelemetry-proto`.
References to `github.com/open-telemetry/opentelemetry-proto` changed to `go.opentelemetry.io/otel/internal/opentelemetry-proto-gen`. (#948)
References to `github.com/open-telemetry/opentelemetry-proto` changed to `go.opentelemetry.io/otel/internal/opentelemetry-proto-gen`. (#942)

### Changed

- Non-nil value structs for key-value pairs will be marshalled using JSON rather than Sprintf. (#948)

### Removed

Expand Down
4 changes: 4 additions & 0 deletions api/kv/kv.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package kv

import (
"encoding/json"
"fmt"
"reflect"

Expand Down Expand Up @@ -138,5 +139,8 @@ func Infer(k string, value interface{}) KeyValue {
case reflect.String:
return String(k, rv.String())
}
if b, err := json.Marshal(value); value != nil && err == nil {
return String(k, string(b))
}
return String(k, fmt.Sprint(value))
}
23 changes: 23 additions & 0 deletions api/kv/kv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,17 @@ func TestKeyValueConstructors(t *testing.T) {
func TestInfer(t *testing.T) {
builder := &strings.Builder{}
builder.WriteString("foo")
jsonifyStruct := struct {
Public string
private string
Tagged string `json:"tagName"`
Empty string
OmitEmpty string `json:",omitempty"`
Omit string `json:"-"`
}{"foo", "bar", "baz", "", "", "omitted"}
invalidStruct := struct {
N complex64
}{complex(0, 0)}
for _, testcase := range []struct {
key string
value interface{}
Expand Down Expand Up @@ -190,6 +201,18 @@ func TestInfer(t *testing.T) {
wantType: value.STRING,
wantValue: "<nil>",
},
{
key: "JSON struct serialized correctly",
value: &jsonifyStruct,
wantType: value.STRING,
wantValue: `{"Public":"foo","tagName":"baz","Empty":""}`,
},
{
key: "Invalid JSON struct falls back to string",
value: &invalidStruct,
wantType: value.STRING,
wantValue: "&{(0+0i)}",
},
} {
t.Logf("Running test case %s", testcase.key)
keyValue := kv.Infer(testcase.key, testcase.value)
Expand Down

0 comments on commit b2b23e1

Please sign in to comment.