1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-02-05 13:15:41 +02:00

supports marshaling values as json (#948)

This commit is contained in:
Liz Fong-Jones 2020-07-17 16:10:19 -04:00 committed by GitHub
parent d6ad4d4d6e
commit b2b23e15e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 32 additions and 1 deletions

View File

@ -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

View File

@ -15,6 +15,7 @@
package kv
import (
"encoding/json"
"fmt"
"reflect"
@ -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))
}

View File

@ -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{}
@ -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)