Skip to content

Commit 417580d

Browse files
authored
add: ContextLogger Interface LogObjectMarshaler (#623)
1 parent 602e90a commit 417580d

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

context.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,9 @@ func (c Context) Durs(key string, d []time.Duration) Context {
391391

392392
// Interface adds the field key with obj marshaled using reflection.
393393
func (c Context) Interface(key string, i interface{}) Context {
394+
if obj, ok := i.(LogObjectMarshaler); ok {
395+
return c.Object(key, obj)
396+
}
394397
c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), i)
395398
return c
396399
}

ctx_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package zerolog
22

33
import (
4+
"bytes"
45
"context"
56
"io"
67
"reflect"
@@ -68,3 +69,31 @@ func TestCtxDisabled(t *testing.T) {
6869
t.Error("WithContext did not override logger with a disabled logger")
6970
}
7071
}
72+
73+
type logObjectMarshalerImpl struct {
74+
name string
75+
age int
76+
}
77+
78+
func (t logObjectMarshalerImpl) MarshalZerologObject(e *Event) {
79+
e.Str("name", "custom_value").Int("age", t.age)
80+
}
81+
82+
func Test_InterfaceLogObjectMarshaler(t *testing.T) {
83+
var buf bytes.Buffer
84+
log := New(&buf)
85+
ctx := log.WithContext(context.Background())
86+
87+
log2 := Ctx(ctx)
88+
89+
withLog := log2.With().Interface("obj", &logObjectMarshalerImpl{
90+
name: "foo",
91+
age: 29,
92+
}).Logger()
93+
94+
withLog.Info().Msg("test")
95+
96+
if got, want := buf.String(), `{"level":"info","obj":{"name":"custom_value","age":29},"message":"test"}`+"\n"; got != want {
97+
t.Errorf("got %q, want %q", got, want)
98+
}
99+
}

0 commit comments

Comments
 (0)