Add a ConsoleWriter to output pretty log on the console during dev

This commit is contained in:
Olivier Poitrey 2017-08-05 19:47:55 -07:00
parent 89ff8dbc5f
commit a83efb6080
3 changed files with 31 additions and 2 deletions

View File

@ -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

9
log.go
View File

@ -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

View File

@ -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()