diff --git a/context.go b/context.go index 0e4f44bb..df352eb6 100644 --- a/context.go +++ b/context.go @@ -391,6 +391,9 @@ func (c Context) Durs(key string, d []time.Duration) Context { // Interface adds the field key with obj marshaled using reflection. func (c Context) Interface(key string, i interface{}) Context { + if obj, ok := i.(LogObjectMarshaler); ok { + return c.Object(key, obj) + } c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), i) return c } diff --git a/ctx_test.go b/ctx_test.go index d024d54a..397e966c 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1,6 +1,7 @@ package zerolog import ( + "bytes" "context" "io" "reflect" @@ -68,3 +69,31 @@ func TestCtxDisabled(t *testing.T) { t.Error("WithContext did not override logger with a disabled logger") } } + +type logObjectMarshalerImpl struct { + name string + age int +} + +func (t logObjectMarshalerImpl) MarshalZerologObject(e *Event) { + e.Str("name", "custom_value").Int("age", t.age) +} + +func Test_InterfaceLogObjectMarshaler(t *testing.T) { + var buf bytes.Buffer + log := New(&buf) + ctx := log.WithContext(context.Background()) + + log2 := Ctx(ctx) + + withLog := log2.With().Interface("obj", &logObjectMarshalerImpl{ + name: "foo", + age: 29, + }).Logger() + + withLog.Info().Msg("test") + + if got, want := buf.String(), `{"level":"info","obj":{"name":"custom_value","age":29},"message":"test"}`+"\n"; got != want { + t.Errorf("got %q, want %q", got, want) + } +}