From 6925dbdff191b554cb2aaddb24a403e1bffda8b6 Mon Sep 17 00:00:00 2001 From: Olivier Poitrey Date: Fri, 19 May 2017 19:56:18 -0700 Subject: [PATCH] Add support for object reflection field --- context.go | 6 ++++++ event.go | 9 +++++++++ log_example_test.go | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/context.go b/context.go index 9eceee2..d3c2c20 100644 --- a/context.go +++ b/context.go @@ -127,3 +127,9 @@ func (c Context) Time(key string, t time.Time) Context { c.l.context = appendTime(c.l.context, key, t) 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 +} diff --git a/event.go b/event.go index 2eca670..0c66bf7 100644 --- a/event.go +++ b/event.go @@ -261,3 +261,12 @@ func (e *Event) Time(key string, t time.Time) *Event { e.buf = appendTime(e.buf, key, t) 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 +} diff --git a/log_example_test.go b/log_example_test.go index d1f5484..0ed99d3 100644 --- a/log_example_test.go +++ b/log_example_test.go @@ -114,6 +114,23 @@ func ExampleEvent_Dict() { // 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() { log := zerolog.New(os.Stdout).With(). Str("foo", "bar"). @@ -126,3 +143,20 @@ func ExampleContext_Dict() { // 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"} +}