From 30c7ed39370964cf9494ccb60fee8083b15d019d Mon Sep 17 00:00:00 2001 From: Matthew Sykes Date: Tue, 22 Sep 2020 12:20:06 -0400 Subject: [PATCH] Add reflect support for json.Marshaler Signed-off-by: Matthew Sykes --- .travis.yml | 9 ++++----- encoder.go | 7 +++++++ encoder_test.go | 7 +++++-- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/.travis.yml b/.travis.yml index b35da29..7ce1f7a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,12 +2,11 @@ language: go matrix: include: - - go: "1.12.x" - install: true - env: GO111MODULE=on - - go: "1.13.x" - env: GO111MODULE=off - go: "1.13.x" install: true + - go: "1.14.x" + install: true + - go: "1.15.x" + install: true script: go test -race ./... diff --git a/encoder.go b/encoder.go index 330554f..9e960cc 100644 --- a/encoder.go +++ b/encoder.go @@ -6,6 +6,7 @@ import ( "bytes" "encoding" "encoding/base64" + "encoding/json" "fmt" "math" "reflect" @@ -249,6 +250,12 @@ func (enc *logfmtEncoder) AppendReflected(value interface{}) error { return err } enc.AppendString(string(b)) + case json.Marshaler: + b, err := v.MarshalJSON() + if err != nil { + return err + } + enc.AppendString(string(b)) default: rvalue := reflect.ValueOf(value) switch rvalue.Kind() { diff --git a/encoder_test.go b/encoder_test.go index 95206e4..639117c 100644 --- a/encoder_test.go +++ b/encoder_test.go @@ -150,9 +150,11 @@ func TestEncoderSimple(t *testing.T) { type stringer string type textMarshaler string +type jsonMarshaler string func (s stringer) String() string { return string(s) } func (t textMarshaler) MarshalText() ([]byte, error) { return []byte(t), nil } +func (j jsonMarshaler) MarshalJSON() ([]byte, error) { return []byte(j), nil } func TestEncoderReflected(t *testing.T) { dummyFunc := func(string) {} @@ -168,6 +170,7 @@ func TestEncoderReflected(t *testing.T) { {"bytes", "bytes", []byte("bytes")}, {"stringer", "my-stringer", stringer("my-stringer")}, {"text marshaler", "marshaled-text", textMarshaler("marshaled-text")}, + {"json marshaler", `"{\"json\":\"data\"}"`, textMarshaler(`{"json":"data"}`)}, {"bool", "true", true}, {"int", "-1", -int(1)}, {"int8", "-8", int8(-8)}, @@ -322,7 +325,7 @@ func TestArrayEncoderComplex(t *testing.T) { f: func(enc zapcore.ArrayEncoder) error { for i := 0; i < 3; i++ { enc.AppendObject(zapcore.ObjectMarshalerFunc(func(oe zapcore.ObjectEncoder) error { - oe.AddInt(string('a'+i), i) + oe.AddInt(string(rune('a'+i)), i) return nil })) } @@ -431,7 +434,7 @@ func TestObjectEncoderComplex(t *testing.T) { for i := 0; i < 3; i++ { enc.AddObject(strconv.Itoa(i), zapcore.ObjectMarshalerFunc(func(oe zapcore.ObjectEncoder) error { for j := 0; j < 3; j++ { - oe.AddInt(string('a'+i*3+j), i*3+j+1) + oe.AddInt(string(rune('a'+i*3+j)), i*3+j+1) } return nil }))