Skip to content

Commit 0dc4c75

Browse files
Hyuga-Tsukuiautarch
authored andcommitted
add: ContextLogger Interface LogObjectMarshaler (#623)
1 parent 21264c7 commit 0dc4c75

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
@@ -401,6 +401,9 @@ func (c Context) Durs(key string, d []time.Duration) Context {
401401

402402
// Interface adds the field key with obj marshaled using reflection.
403403
func (c Context) Interface(key string, i interface{}) Context {
404+
if obj, ok := i.(LogObjectMarshaler); ok {
405+
return c.Object(key, obj)
406+
}
404407
c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), i)
405408
return c
406409
}

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

0 commit comments

Comments
 (0)