Add support for object reflection field

This commit is contained in:
Olivier Poitrey 2017-05-19 19:56:18 -07:00
parent d0cfcbbafe
commit 6925dbdff1
3 changed files with 49 additions and 0 deletions

View File

@ -127,3 +127,9 @@ func (c Context) Time(key string, t time.Time) Context {
c.l.context = appendTime(c.l.context, key, t) c.l.context = appendTime(c.l.context, key, t)
return c return c
} }
// Object adds the field key with obj marshaled using reflection.
func (c Context) Object(key string, obj interface{}) Context {
c.l.context = appendObject(c.l.context, key, obj)
return c
}

View File

@ -261,3 +261,12 @@ func (e *Event) Time(key string, t time.Time) *Event {
e.buf = appendTime(e.buf, key, t) e.buf = appendTime(e.buf, key, t)
return e return e
} }
// Object adds the field key with obj marshaled using reflection.
func (e *Event) Object(key string, obj interface{}) *Event {
if !e.enabled {
return e
}
e.buf = appendObject(e.buf, key, obj)
return e
}

View File

@ -114,6 +114,23 @@ func ExampleEvent_Dict() {
// Output: {"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"} // Output: {"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}
} }
func ExampleEvent_Object() {
log := zerolog.New(os.Stdout)
obj := struct {
Name string `json:"name"`
}{
Name: "john",
}
log.Log().
Str("foo", "bar").
Object("obj", obj).
Msg("hello world")
// Output: {"foo":"bar","obj":{"name":"john"},"message":"hello world"}
}
func ExampleContext_Dict() { func ExampleContext_Dict() {
log := zerolog.New(os.Stdout).With(). log := zerolog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
@ -126,3 +143,20 @@ func ExampleContext_Dict() {
// Output: {"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"} // Output: {"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}
} }
func ExampleContext_Object() {
obj := struct {
Name string `json:"name"`
}{
Name: "john",
}
log := zerolog.New(os.Stdout).With().
Str("foo", "bar").
Object("obj", obj).
Logger()
log.Log().Msg("hello world")
// Output: {"foo":"bar","obj":{"name":"john"},"message":"hello world"}
}