From 5d9d7660ccbbb2a32d2ff66840a106ddfb1757ca Mon Sep 17 00:00:00 2001 From: Olivier Poitrey Date: Mon, 18 Nov 2019 16:22:50 -0800 Subject: [PATCH] Expose the Err helper from the global logger --- log/log.go | 8 ++++++++ log/log_example_test.go | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/log/log.go b/log/log.go index d3e12d0..b96f1c1 100644 --- a/log/log.go +++ b/log/log.go @@ -37,6 +37,14 @@ func Hook(h zerolog.Hook) zerolog.Logger { return Logger.Hook(h) } +// Err starts a new message with error level with err as a field if not nil or +// with info level if err is nil. +// +// You must call Msg on the returned event in order to send the event. +func Err(err error) *zerolog.Event { + return Logger.Err(err) +} + // Trace starts a new message with trace level. // // You must call Msg on the returned event in order to send the event. diff --git a/log/log_example_test.go b/log/log_example_test.go index 3127e51..8ed323b 100644 --- a/log/log_example_test.go +++ b/log/log_example_test.go @@ -54,6 +54,17 @@ func ExampleLog() { // Output: {"time":1199811905,"message":"hello world"} } +// Example of a conditional level based on the presence of an error. +func ExampleErr() { + setup() + err := errors.New("some error") + log.Err(err).Msg("hello world") + log.Err(nil).Msg("hello world") + + // Output: {"level":"error","error":"some error","time":1199811905,"message":"hello world"} + // {"level":"info","time":1199811905,"message":"hello world"} +} + // Example of a log at a particular "level" (in this case, "trace") func ExampleTrace() { setup()