From a83efb608038d1073da5ce55fee1dbf69e4a6b0a Mon Sep 17 00:00:00 2001 From: Olivier Poitrey Date: Sat, 5 Aug 2017 19:47:55 -0700 Subject: [PATCH] Add a ConsoleWriter to output pretty log on the console during dev --- README.md | 18 ++++++++++++++++-- log.go | 9 +++++++++ log/log.go | 6 ++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b621336..9a401cc 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,18 @@ Zerolog's API is designed to provide both a great developer experience and stunn The uber's [zap](https://godoc.org/go.uber.org/zap) library pioneered this approach. Zerolog is taking this concept to the next level with simpler to use API and even better performance. -To keep the code base and the API simple, zerolog focuses on JSON logging only. As [suggested on reddit](https://www.reddit.com/r/golang/comments/6c9k7n/zerolog_is_now_faster_than_zap/), you may use tools like [humanlog](https://github.com/aybabtme/humanlog) to pretty print JSON on the console during development. - +To keep the code base and the API simple, zerolog focuses on JSON logging only. Pretty logging on the console is made possible using the provided `zerolog.ConsoleWriter`. ## Features +* Blazing fast +* Low to zero allocation * Level logging * Sampling * Contextual fields * `context.Context` integration * `net/http` helpers +* Pretty logging for development ## Usage @@ -96,6 +98,18 @@ if e := log.Debug(); e.Enabled() { // Output: {"level":"info","time":1494567715,"message":"routed message"} ``` +### Pretty logging + +```go +if isConsole { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) +} + +log.Info().Str("foo", "bar").Msg("Hello world") + +// Output: 1494567715 |INFO| Hello world foo=bar +``` + ### Sub dictionary ```go diff --git a/log.go b/log.go index 71db0b5..e3c590f 100644 --- a/log.go +++ b/log.go @@ -162,6 +162,15 @@ func Nop() Logger { return New(nil).Level(Disabled) } +// Output duplicates the current logger and sets w as its output. +func (l Logger) Output(w io.Writer) Logger { + l2 := New(w) + l2.level = l.level + l2.sample = l.sample + copy(l2.context, l.context) + return l2 +} + // With creates a child logger with the field added to its context. func (l Logger) With() Context { context := l.context diff --git a/log/log.go b/log/log.go index a478596..d705aa9 100644 --- a/log/log.go +++ b/log/log.go @@ -3,6 +3,7 @@ package log import ( "context" + "io" "os" "github.com/rs/zerolog" @@ -11,6 +12,11 @@ import ( // Logger is the global logger. var Logger = zerolog.New(os.Stderr).With().Timestamp().Logger() +// Output duplicates the global logger and sets w as its output. +func Output(w io.Writer) zerolog.Logger { + return Logger.Output(w) +} + // With creates a child logger with the field added to its context. func With() zerolog.Context { return Logger.With()