change log

This commit is contained in:
elee 2022-03-20 14:19:42 -05:00
parent e9344a8c50
commit c7d28c47c7
49 changed files with 426 additions and 390 deletions

2
CNAME
View File

@ -1 +1 @@
zerolog.io zlog.io

194
README.md
View File

@ -1,20 +1,20 @@
# Zero Allocation JSON Logger # Zero Allocation JSON Logger
[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/zerolog) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/zerolog/master/LICENSE) [![Build Status](https://travis-ci.org/rs/zerolog.svg?branch=master)](https://travis-ci.org/rs/zerolog) [![Coverage](http://gocover.io/_badge/github.com/rs/zerolog)](http://gocover.io/github.com/rs/zerolog) [![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/git.tuxpa.in/a/zlog) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/zlog/master/LICENSE) [![Build Status](https://travis-ci.org/rs/zlog.svg?branch=master)](https://travis-ci.org/rs/zlog) [![Coverage](http://gocover.io/_badge/git.tuxpa.in/a/zlog)](http://gocover.io/git.tuxpa.in/a/zlog)
The zerolog package provides a fast and simple logger dedicated to JSON output. The zlog package provides a fast and simple logger dedicated to JSON output.
Zerolog's API is designed to provide both a great developer experience and stunning [performance](#benchmarks). Its unique chaining API allows zerolog to write JSON (or CBOR) log events by avoiding allocations and reflection. Zerolog's API is designed to provide both a great developer experience and stunning [performance](#benchmarks). Its unique chaining API allows zlog to write JSON (or CBOR) log events by avoiding allocations and reflection.
Uber's [zap](https://godoc.org/go.uber.org/zap) library pioneered this approach. Zerolog is taking this concept to the next level with a simpler to use API and even better performance. Uber's [zap](https://godoc.org/go.uber.org/zap) library pioneered this approach. Zerolog is taking this concept to the next level with a simpler to use API and even better performance.
To keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) [`zerolog.ConsoleWriter`](#pretty-logging). To keep the code base and the API simple, zlog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) [`zlog.ConsoleWriter`](#pretty-logging).
![Pretty Logging Image](pretty.png) ![Pretty Logging Image](pretty.png)
## Who uses zerolog ## Who uses zlog
Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog) and add your company / project to the list. Find out [who uses zlog](https://git.tuxpa.in/a/zlog/wiki/Who-uses-zlog) and add your company / project to the list.
## Features ## Features
@ -33,26 +33,26 @@ Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog)
## Installation ## Installation
```bash ```bash
go get -u github.com/rs/zerolog/log go get -u git.tuxpa.in/a/zlog/log
``` ```
## Getting Started ## Getting Started
### Simple Logging Example ### Simple Logging Example
For simple logging, import the global logger package **github.com/rs/zerolog/log** For simple logging, import the global logger package **git.tuxpa.in/a/zlog/log**
```go ```go
package main package main
import ( import (
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
func main() { func main() {
// UNIX Time is faster and smaller than most timestamps // UNIX Time is faster and smaller than most timestamps
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Print("hello world") log.Print("hello world")
} }
@ -64,18 +64,18 @@ func main() {
### Contextual Logging ### Contextual Logging
**zerolog** allows data to be added to log messages in the form of key:value pairs. The data added to the message adds "context" about the log event that can be critical for debugging as well as myriad other purposes. An example of this is below: **zlog** allows data to be added to log messages in the form of key:value pairs. The data added to the message adds "context" about the log event that can be critical for debugging as well as myriad other purposes. An example of this is below:
```go ```go
package main package main
import ( import (
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
func main() { func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Debug(). log.Debug().
Str("Scale", "833 cents"). Str("Scale", "833 cents").
@ -101,12 +101,12 @@ func main() {
package main package main
import ( import (
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
func main() { func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Info().Msg("hello world") log.Info().Msg("hello world")
} }
@ -114,19 +114,19 @@ func main() {
// Output: {"time":1516134303,"level":"info","message":"hello world"} // Output: {"time":1516134303,"level":"info","message":"hello world"}
``` ```
> It is very important to note that when using the **zerolog** chaining API, as shown above (`log.Info().Msg("hello world"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this. > It is very important to note that when using the **zlog** chaining API, as shown above (`log.Info().Msg("hello world"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this.
**zerolog** allows for logging at the following levels (from highest to lowest): **zlog** allows for logging at the following levels (from highest to lowest):
* panic (`zerolog.PanicLevel`, 5) * panic (`zlog.PanicLevel`, 5)
* fatal (`zerolog.FatalLevel`, 4) * fatal (`zlog.FatalLevel`, 4)
* error (`zerolog.ErrorLevel`, 3) * error (`zlog.ErrorLevel`, 3)
* warn (`zerolog.WarnLevel`, 2) * warn (`zlog.WarnLevel`, 2)
* info (`zerolog.InfoLevel`, 1) * info (`zlog.InfoLevel`, 1)
* debug (`zerolog.DebugLevel`, 0) * debug (`zlog.DebugLevel`, 0)
* trace (`zerolog.TraceLevel`, -1) * trace (`zlog.TraceLevel`, -1)
You can set the Global logging level to any of these options using the `SetGlobalLevel` function in the zerolog package, passing in one of the given constants above, e.g. `zerolog.InfoLevel` would be the "info" level. Whichever level is chosen, all logs with a level greater than or equal to that level will be written. To turn off logging entirely, pass the `zerolog.Disabled` constant. You can set the Global logging level to any of these options using the `SetGlobalLevel` function in the zlog package, passing in one of the given constants above, e.g. `zlog.InfoLevel` would be the "info" level. Whichever level is chosen, all logs with a level greater than or equal to that level will be written. To turn off logging entirely, pass the `zlog.Disabled` constant.
#### Setting Global Log Level #### Setting Global Log Level
@ -138,20 +138,20 @@ package main
import ( import (
"flag" "flag"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
func main() { func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
debug := flag.Bool("debug", false, "sets log level to debug") debug := flag.Bool("debug", false, "sets log level to debug")
flag.Parse() flag.Parse()
// Default level for this example is info, unless debug flag is present // Default level for this example is info, unless debug flag is present
zerolog.SetGlobalLevel(zerolog.InfoLevel) zlog.SetGlobalLevel(zlog.InfoLevel)
if *debug { if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel) zlog.SetGlobalLevel(zlog.DebugLevel)
} }
log.Debug().Msg("This message appears only when log level set to Debug") log.Debug().Msg("This message appears only when log level set to Debug")
@ -189,12 +189,12 @@ You may choose to log without a specific level by using the `Log` method. You ma
package main package main
import ( import (
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
func main() { func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
@ -214,12 +214,12 @@ package main
import ( import (
"errors" "errors"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
func main() { func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
err := errors.New("seems we have an error here") err := errors.New("seems we have an error here")
log.Error().Err(err).Msg("") log.Error().Err(err).Msg("")
@ -228,7 +228,7 @@ func main() {
// Output: {"level":"error","error":"seems we have an error here","time":1609085256} // Output: {"level":"error","error":"seems we have an error here","time":1609085256}
``` ```
> The default field name for errors is `error`, you can change this by setting `zerolog.ErrorFieldName` to meet your needs. > The default field name for errors is `error`, you can change this by setting `zlog.ErrorFieldName` to meet your needs.
#### Error Logging with Stacktrace #### Error Logging with Stacktrace
@ -239,15 +239,15 @@ package main
import ( import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/rs/zerolog/pkgerrors" "git.tuxpa.in/a/zlog/pkgerrors"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
func main() { func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack zlog.ErrorStackMarshaler = pkgerrors.MarshalStack
err := outer() err := outer()
log.Error().Stack().Err(err).Msg("") log.Error().Stack().Err(err).Msg("")
@ -276,7 +276,7 @@ func outer() error {
// Output: {"level":"error","stack":[{"func":"inner","line":"20","source":"errors.go"},{"func":"middle","line":"24","source":"errors.go"},{"func":"outer","line":"32","source":"errors.go"},{"func":"main","line":"15","source":"errors.go"},{"func":"main","line":"204","source":"proc.go"},{"func":"goexit","line":"1374","source":"asm_amd64.s"}],"error":"seems we have an error here","time":1609086683} // Output: {"level":"error","stack":[{"func":"inner","line":"20","source":"errors.go"},{"func":"middle","line":"24","source":"errors.go"},{"func":"outer","line":"32","source":"errors.go"},{"func":"main","line":"15","source":"errors.go"},{"func":"main","line":"204","source":"proc.go"},{"func":"goexit","line":"1374","source":"asm_amd64.s"}],"error":"seems we have an error here","time":1609086683}
``` ```
> zerolog.ErrorStackMarshaler must be set in order for the stack to output anything. > zlog.ErrorStackMarshaler must be set in order for the stack to output anything.
#### Logging Fatal Messages #### Logging Fatal Messages
@ -286,15 +286,15 @@ package main
import ( import (
"errors" "errors"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
func main() { func main() {
err := errors.New("A repo man spends his life getting into tense situations") err := errors.New("A repo man spends his life getting into tense situations")
service := "myservice" service := "myservice"
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Fatal(). log.Fatal().
Err(err). Err(err).
@ -312,7 +312,7 @@ func main() {
### Create logger instance to manage different outputs ### Create logger instance to manage different outputs
```go ```go
logger := zerolog.New(os.Stderr).With().Timestamp().Logger() logger := zlog.New(os.Stderr).With().Timestamp().Logger()
logger.Info().Str("foo", "bar").Msg("hello world") logger.Info().Str("foo", "bar").Msg("hello world")
@ -332,10 +332,10 @@ sublogger.Info().Msg("hello world")
### Pretty logging ### Pretty logging
To log a human-friendly, colorized output, use `zerolog.ConsoleWriter`: To log a human-friendly, colorized output, use `zlog.ConsoleWriter`:
```go ```go
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) log.Logger = log.Output(zlog.ConsoleWriter{Out: os.Stderr})
log.Info().Str("foo", "bar").Msg("Hello world") log.Info().Str("foo", "bar").Msg("Hello world")
@ -345,7 +345,7 @@ log.Info().Str("foo", "bar").Msg("Hello world")
To customize the configuration and formatting: To customize the configuration and formatting:
```go ```go
output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339} output := zlog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
output.FormatLevel = func(i interface{}) string { output.FormatLevel = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("| %-6s|", i)) return strings.ToUpper(fmt.Sprintf("| %-6s|", i))
} }
@ -359,7 +359,7 @@ output.FormatFieldValue = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("%s", i)) return strings.ToUpper(fmt.Sprintf("%s", i))
} }
log := zerolog.New(output).With().Timestamp().Logger() log := zlog.New(output).With().Timestamp().Logger()
log.Info().Str("foo", "bar").Msg("Hello World") log.Info().Str("foo", "bar").Msg("Hello World")
@ -371,7 +371,7 @@ log.Info().Str("foo", "bar").Msg("Hello World")
```go ```go
log.Info(). log.Info().
Str("foo", "bar"). Str("foo", "bar").
Dict("dict", zerolog.Dict(). Dict("dict", zlog.Dict().
Str("bar", "baz"). Str("bar", "baz").
Int("n", 1), Int("n", 1),
).Msg("hello world") ).Msg("hello world")
@ -382,9 +382,9 @@ log.Info().
### Customize automatic field names ### Customize automatic field names
```go ```go
zerolog.TimestampFieldName = "t" zlog.TimestampFieldName = "t"
zerolog.LevelFieldName = "l" zlog.LevelFieldName = "l"
zerolog.MessageFieldName = "m" zlog.MessageFieldName = "m"
log.Info().Msg("hello world") log.Info().Msg("hello world")
@ -411,7 +411,7 @@ log.Info().Msg("hello world")
Equivalent of `Lshortfile`: Equivalent of `Lshortfile`:
```go ```go
zerolog.CallerMarshalFunc = func(file string, line int) string { zlog.CallerMarshalFunc = func(file string, line int) string {
short := file short := file
for i := len(file) - 1; i > 0; i-- { for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' { if file[i] == '/' {
@ -436,7 +436,7 @@ If your writer might be slow or not thread-safe and you need your log producers
wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) { wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) {
fmt.Printf("Logger Dropped %d messages", missed) fmt.Printf("Logger Dropped %d messages", missed)
}) })
log := zerolog.New(wr) log := zlog.New(wr)
log.Print("test") log.Print("test")
``` ```
@ -445,7 +445,7 @@ You will need to install `code.cloudfoundry.org/go-diodes` to use this feature.
### Log Sampling ### Log Sampling
```go ```go
sampled := log.Sample(&zerolog.BasicSampler{N: 10}) sampled := log.Sample(&zlog.BasicSampler{N: 10})
sampled.Info().Msg("will be logged every 10 messages") sampled.Info().Msg("will be logged every 10 messages")
// Output: {"time":1494567715,"level":"info","message":"will be logged every 10 messages"} // Output: {"time":1494567715,"level":"info","message":"will be logged every 10 messages"}
@ -457,11 +457,11 @@ More advanced sampling:
// Will let 5 debug messages per period of 1 second. // Will let 5 debug messages per period of 1 second.
// Over 5 debug message, 1 every 100 debug messages are logged. // Over 5 debug message, 1 every 100 debug messages are logged.
// Other levels are not sampled. // Other levels are not sampled.
sampled := log.Sample(zerolog.LevelSampler{ sampled := log.Sample(zlog.LevelSampler{
DebugSampler: &zerolog.BurstSampler{ DebugSampler: &zlog.BurstSampler{
Burst: 5, Burst: 5,
Period: 1*time.Second, Period: 1*time.Second,
NextSampler: &zerolog.BasicSampler{N: 100}, NextSampler: &zlog.BasicSampler{N: 100},
}, },
}) })
sampled.Debug().Msg("hello world") sampled.Debug().Msg("hello world")
@ -474,8 +474,8 @@ sampled.Debug().Msg("hello world")
```go ```go
type SeverityHook struct{} type SeverityHook struct{}
func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) { func (h SeverityHook) Run(e *zlog.Event, level zlog.Level, msg string) {
if level != zerolog.NoLevel { if level != zlog.NoLevel {
e.Str("severity", level.String()) e.Str("severity", level.String())
} }
} }
@ -499,7 +499,7 @@ log.Ctx(ctx).Info().Msg("hello world")
### Set as standard logger output ### Set as standard logger output
```go ```go
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
@ -513,12 +513,12 @@ stdlog.Print("hello world")
### Integration with `net/http` ### Integration with `net/http`
The `github.com/rs/zerolog/hlog` package provides some helpers to integrate zerolog with `http.Handler`. The `git.tuxpa.in/a/zlog/hlog` package provides some helpers to integrate zlog with `http.Handler`.
In this example we use [alice](https://github.com/justinas/alice) to install logger for better readability. In this example we use [alice](https://github.com/justinas/alice) to install logger for better readability.
```go ```go
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Timestamp(). Timestamp().
Str("role", "my-service"). Str("role", "my-service").
Str("host", host). Str("host", host).
@ -565,15 +565,15 @@ if err := http.ListenAndServe(":8080", nil); err != nil {
``` ```
## Multiple Log Output ## Multiple Log Output
`zerolog.MultiLevelWriter` may be used to send the log message to multiple outputs. `zlog.MultiLevelWriter` may be used to send the log message to multiple outputs.
In this example, we send the log message to both `os.Stdout` and the in-built ConsoleWriter. In this example, we send the log message to both `os.Stdout` and the in-built ConsoleWriter.
```go ```go
func main() { func main() {
consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout} consoleWriter := zlog.ConsoleWriter{Out: os.Stdout}
multi := zerolog.MultiLevelWriter(consoleWriter, os.Stdout) multi := zlog.MultiLevelWriter(consoleWriter, os.Stdout)
logger := zerolog.New(multi).With().Timestamp().Logger() logger := zlog.New(multi).With().Timestamp().Logger()
logger.Info().Msg("Hello World!") logger.Info().Msg("Hello World!")
} }
@ -588,16 +588,16 @@ func main() {
Some settings can be changed and will be applied to all loggers: Some settings can be changed and will be applied to all loggers:
* `log.Logger`: You can set this value to customize the global logger (the one used by package level methods). * `log.Logger`: You can set this value to customize the global logger (the one used by package level methods).
* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zerolog.Disabled` to disable logging altogether (quiet mode). * `zlog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zlog.Disabled` to disable logging altogether (quiet mode).
* `zerolog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events. * `zlog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events.
* `zerolog.TimestampFieldName`: Can be set to customize `Timestamp` field name. * `zlog.TimestampFieldName`: Can be set to customize `Timestamp` field name.
* `zerolog.LevelFieldName`: Can be set to customize level field name. * `zlog.LevelFieldName`: Can be set to customize level field name.
* `zerolog.MessageFieldName`: Can be set to customize message field name. * `zlog.MessageFieldName`: Can be set to customize message field name.
* `zerolog.ErrorFieldName`: Can be set to customize `Err` field name. * `zlog.ErrorFieldName`: Can be set to customize `Err` field name.
* `zerolog.TimeFieldFormat`: Can be set to customize `Time` field value formatting. If set with `zerolog.TimeFormatUnix`, `zerolog.TimeFormatUnixMs` or `zerolog.TimeFormatUnixMicro`, times are formated as UNIX timestamp. * `zlog.TimeFieldFormat`: Can be set to customize `Time` field value formatting. If set with `zlog.TimeFormatUnix`, `zlog.TimeFormatUnixMs` or `zlog.TimeFormatUnixMicro`, times are formated as UNIX timestamp.
* `zerolog.DurationFieldUnit`: Can be set to customize the unit for time.Duration type fields added by `Dur` (default: `time.Millisecond`). * `zlog.DurationFieldUnit`: Can be set to customize the unit for time.Duration type fields added by `Dur` (default: `time.Millisecond`).
* `zerolog.DurationFieldInteger`: If set to `true`, `Dur` fields are formatted as integers instead of floats (default: `false`). * `zlog.DurationFieldInteger`: If set to `true`, `Dur` fields are formatted as integers instead of floats (default: `false`).
* `zerolog.ErrorHandler`: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking. * `zlog.ErrorHandler`: Called whenever zlog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking.
## Field Types ## Field Types
@ -611,10 +611,10 @@ Some settings can be changed and will be applied to all loggers:
### Advanced Fields ### Advanced Fields
* `Err`: Takes an `error` and renders it as a string using the `zerolog.ErrorFieldName` field name. * `Err`: Takes an `error` and renders it as a string using the `zlog.ErrorFieldName` field name.
* `Func`: Run a `func` only if the level is enabled. * `Func`: Run a `func` only if the level is enabled.
* `Timestamp`: Inserts a timestamp field with `zerolog.TimestampFieldName` field name, formatted using `zerolog.TimeFieldFormat`. * `Timestamp`: Inserts a timestamp field with `zlog.TimestampFieldName` field name, formatted using `zlog.TimeFieldFormat`.
* `Time`: Adds a field with time formatted with `zerolog.TimeFieldFormat`. * `Time`: Adds a field with time formatted with `zlog.TimeFieldFormat`.
* `Dur`: Adds a field with `time.Duration`. * `Dur`: Adds a field with `time.Duration`.
* `Dict`: Adds a sub-key/value as a field of the event. * `Dict`: Adds a sub-key/value as a field of the event.
* `RawJSON`: Adds a field with an already encoded JSON (`[]byte`) * `RawJSON`: Adds a field with an already encoded JSON (`[]byte`)
@ -625,20 +625,20 @@ Most fields are also available in the slice format (`Strs` for `[]string`, `Errs
## Binary Encoding ## Binary Encoding
In addition to the default JSON encoding, `zerolog` can produce binary logs using [CBOR](http://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows: In addition to the default JSON encoding, `zlog` can produce binary logs using [CBOR](http://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows:
```bash ```bash
go build -tags binary_log . go build -tags binary_log .
``` ```
To Decode binary encoded log files you can use any CBOR decoder. One has been tested to work To Decode binary encoded log files you can use any CBOR decoder. One has been tested to work
with zerolog library is [CSD](https://github.com/toravir/csd/). with zlog library is [CSD](https://github.com/toravir/csd/).
## Related Projects ## Related Projects
* [grpc-zerolog](https://github.com/cheapRoc/grpc-zerolog): Implementation of `grpclog.LoggerV2` interface using `zerolog` * [grpc-zlog](https://github.com/cheapRoc/grpc-zlog): Implementation of `grpclog.LoggerV2` interface using `zlog`
* [overlog](https://github.com/Trendyol/overlog): Implementation of `Mapped Diagnostic Context` interface using `zerolog` * [overlog](https://github.com/Trendyol/overlog): Implementation of `Mapped Diagnostic Context` interface using `zlog`
* [zerologr](https://github.com/go-logr/zerologr): Implementation of `logr.LogSink` interface using `zerolog` * [zlogr](https://github.com/go-logr/zlogr): Implementation of `logr.LogSink` interface using `zlog`
## Benchmarks ## Benchmarks
@ -654,7 +654,7 @@ BenchmarkContextFields-8 30000000 44.9 ns/op 0 B/op 0 allocs/op
BenchmarkLogFields-8 10000000 184 ns/op 0 B/op 0 allocs/op BenchmarkLogFields-8 10000000 184 ns/op 0 B/op 0 allocs/op
``` ```
There are a few Go logging benchmarks and comparisons that include zerolog. There are a few Go logging benchmarks and comparisons that include zlog.
* [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench) * [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench)
* [uber-common/zap](https://github.com/uber-go/zap#performance) * [uber-common/zap](https://github.com/uber-go/zap#performance)
@ -665,7 +665,7 @@ Log a message and 10 fields:
| Library | Time | Bytes Allocated | Objects Allocated | | Library | Time | Bytes Allocated | Objects Allocated |
| :--- | :---: | :---: | :---: | | :--- | :---: | :---: | :---: |
| zerolog | 767 ns/op | 552 B/op | 6 allocs/op | | zlog | 767 ns/op | 552 B/op | 6 allocs/op |
| :zap: zap | 848 ns/op | 704 B/op | 2 allocs/op | | :zap: zap | 848 ns/op | 704 B/op | 2 allocs/op |
| :zap: zap (sugared) | 1363 ns/op | 1610 B/op | 20 allocs/op | | :zap: zap (sugared) | 1363 ns/op | 1610 B/op | 20 allocs/op |
| go-kit | 3614 ns/op | 2895 B/op | 66 allocs/op | | go-kit | 3614 ns/op | 2895 B/op | 66 allocs/op |
@ -678,7 +678,7 @@ Log a message with a logger that already has 10 fields of context:
| Library | Time | Bytes Allocated | Objects Allocated | | Library | Time | Bytes Allocated | Objects Allocated |
| :--- | :---: | :---: | :---: | | :--- | :---: | :---: | :---: |
| zerolog | 52 ns/op | 0 B/op | 0 allocs/op | | zlog | 52 ns/op | 0 B/op | 0 allocs/op |
| :zap: zap | 283 ns/op | 0 B/op | 0 allocs/op | | :zap: zap | 283 ns/op | 0 B/op | 0 allocs/op |
| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op | | :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op |
| lion | 2702 ns/op | 4074 B/op | 38 allocs/op | | lion | 2702 ns/op | 4074 B/op | 38 allocs/op |
@ -691,7 +691,7 @@ Log a static string, without any context or `printf`-style templating:
| Library | Time | Bytes Allocated | Objects Allocated | | Library | Time | Bytes Allocated | Objects Allocated |
| :--- | :---: | :---: | :---: | | :--- | :---: | :---: | :---: |
| zerolog | 50 ns/op | 0 B/op | 0 allocs/op | | zlog | 50 ns/op | 0 B/op | 0 allocs/op |
| :zap: zap | 236 ns/op | 0 B/op | 0 allocs/op | | :zap: zap | 236 ns/op | 0 B/op | 0 allocs/op |
| standard library | 453 ns/op | 80 B/op | 2 allocs/op | | standard library | 453 ns/op | 80 B/op | 2 allocs/op |
| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op | | :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op |
@ -703,10 +703,10 @@ Log a static string, without any context or `printf`-style templating:
## Caveats ## Caveats
Note that zerolog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON: Note that zlog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON:
```go ```go
logger := zerolog.New(os.Stderr).With().Timestamp().Logger() logger := zlog.New(os.Stderr).With().Timestamp().Logger()
logger.Info(). logger.Info().
Timestamp(). Timestamp().
Msg("dup") Msg("dup")

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"net" "net"
@ -193,7 +193,7 @@ func (a *Array) Float64(f float64) *Array {
return a return a
} }
// Time append append t formatted as string using zerolog.TimeFieldFormat. // Time append append t formatted as string using zlog.TimeFieldFormat.
func (a *Array) Time(t time.Time) *Array { func (a *Array) Time(t time.Time) *Array {
a.buf = enc.AppendTime(enc.AppendArrayDelim(a.buf), t, TimeFieldFormat) a.buf = enc.AppendTime(enc.AppendArrayDelim(a.buf), t, TimeFieldFormat)
return a return a

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"net" "net"

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"errors" "errors"

View File

@ -1,6 +1,6 @@
// +build binary_log // +build binary_log
package zerolog package zlog
import ( import (
"bytes" "bytes"

View File

@ -4,13 +4,13 @@ This is a basic linter that checks for missing log event finishers. Finds errors
## Problem ## Problem
When using zerolog it's easy to forget to finish the log event chain by calling a finisher - the `Msg` or `Msgf` function that will schedule the event for writing. The problem with this is that it doesn't warn/panic during compilation and it's not easily found by grep or other general tools. It's even prominently mentioned in the project's readme, that: When using zlog it's easy to forget to finish the log event chain by calling a finisher - the `Msg` or `Msgf` function that will schedule the event for writing. The problem with this is that it doesn't warn/panic during compilation and it's not easily found by grep or other general tools. It's even prominently mentioned in the project's readme, that:
> It is very important to note that when using the **zerolog** chaining API, as shown above (`log.Info().Msg("hello world"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this. > It is very important to note that when using the **zlog** chaining API, as shown above (`log.Info().Msg("hello world"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this.
## Solution ## Solution
A basic linter like this one here that looks for method invocations on `zerolog.Event` can examine the last call in a method call chain and check if it is a finisher, thus pointing out these errors. A basic linter like this one here that looks for method invocations on `zlog.Event` can examine the last call in a method call chain and check if it is a finisher, thus pointing out these errors.
## Usage ## Usage
@ -33,5 +33,5 @@ The command accepts only one argument - the package to be inspected - and 4 opti
## Drawbacks ## Drawbacks
As it is, linter can generate a false positives in a specific case. These false positives come from the fact that if you have a method that returns a `zerolog.Event` the linter will flag it because you are obviously not finishing the event. This will be solved in later release. As it is, linter can generate a false positives in a specific case. These false positives come from the fact that if you have a method that returns a `zlog.Event` the linter will flag it because you are obviously not finishing the event. This will be solved in later release.

View File

@ -1,4 +1,4 @@
module github.com/rs/zerolog/cmd/lint module git.tuxpa.in/a/zlog/cmd/lint
go 1.15 go 1.15

View File

@ -29,8 +29,8 @@ func init() {
flag.Var(&allowedFinishers, "finisher", "allowed finisher for the event chain") flag.Var(&allowedFinishers, "finisher", "allowed finisher for the event chain")
flag.Parse() flag.Parse()
// add zerolog to recursively ignored packages // add zlog to recursively ignored packages
recursivelyIgnoredPkgs = append(recursivelyIgnoredPkgs, "github.com/rs/zerolog") recursivelyIgnoredPkgs = append(recursivelyIgnoredPkgs, "git.tuxpa.in/a/zlog")
args := flag.Args() args := flag.Args()
if len(args) != 1 { if len(args) != 1 {
fmt.Fprintln(os.Stderr, "you must provide exactly one package path") fmt.Fprintln(os.Stderr, "you must provide exactly one package path")
@ -49,14 +49,14 @@ func main() {
os.Exit(1) os.Exit(1)
} }
// get the github.com/rs/zerolog.Event type // get the git.tuxpa.in/a/zlog.Event type
event := getEvent(p) event := getEvent(p)
if event == nil { if event == nil {
fmt.Fprintln(os.Stderr, "Error: github.com/rs/zerolog.Event declaration not found, maybe zerolog is not imported in the scanned package?") fmt.Fprintln(os.Stderr, "Error: git.tuxpa.in/a/zlog.Event declaration not found, maybe zlog is not imported in the scanned package?")
os.Exit(1) os.Exit(1)
} }
// get all selections (function calls) with the github.com/rs/zerolog.Event (or pointer) receiver // get all selections (function calls) with the git.tuxpa.in/a/zlog.Event (or pointer) receiver
selections := getSelectionsWithReceiverType(p, event) selections := getSelectionsWithReceiverType(p, event)
// print the violations (if any) // print the violations (if any)
@ -80,7 +80,7 @@ func main() {
func getEvent(p *loader.Program) types.Type { func getEvent(p *loader.Program) types.Type {
for _, pkg := range p.AllPackages { for _, pkg := range p.AllPackages {
if strings.HasSuffix(pkg.Pkg.Path(), "github.com/rs/zerolog") { if strings.HasSuffix(pkg.Pkg.Path(), "git.tuxpa.in/a/zlog") {
for _, d := range pkg.Defs { for _, d := range pkg.Defs {
if d != nil && d.Name() == "Event" { if d != nil && d.Name() == "Event" {
return d.Type() return d.Type()

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"bytes" "bytes"

View File

@ -1,4 +1,4 @@
package zerolog_test package zlog_test
import ( import (
"bytes" "bytes"
@ -9,39 +9,39 @@ import (
"testing" "testing"
"time" "time"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
) )
func ExampleConsoleWriter() { func ExampleConsoleWriter() {
log := zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true}) log := zlog.New(zlog.ConsoleWriter{Out: os.Stdout, NoColor: true})
log.Info().Str("foo", "bar").Msg("Hello World") log.Info().Str("foo", "bar").Msg("Hello World")
// Output: <nil> INF Hello World foo=bar // Output: <nil> INF Hello World foo=bar
} }
func ExampleConsoleWriter_customFormatters() { func ExampleConsoleWriter_customFormatters() {
out := zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true} out := zlog.ConsoleWriter{Out: os.Stdout, NoColor: true}
out.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%-6s|", i)) } out.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%-6s|", i)) }
out.FormatFieldName = func(i interface{}) string { return fmt.Sprintf("%s:", i) } out.FormatFieldName = func(i interface{}) string { return fmt.Sprintf("%s:", i) }
out.FormatFieldValue = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%s", i)) } out.FormatFieldValue = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%s", i)) }
log := zerolog.New(out) log := zlog.New(out)
log.Info().Str("foo", "bar").Msg("Hello World") log.Info().Str("foo", "bar").Msg("Hello World")
// Output: <nil> INFO | Hello World foo:BAR // Output: <nil> INFO | Hello World foo:BAR
} }
func ExampleNewConsoleWriter() { func ExampleNewConsoleWriter() {
out := zerolog.NewConsoleWriter() out := zlog.NewConsoleWriter()
out.NoColor = true // For testing purposes only out.NoColor = true // For testing purposes only
log := zerolog.New(out) log := zlog.New(out)
log.Debug().Str("foo", "bar").Msg("Hello World") log.Debug().Str("foo", "bar").Msg("Hello World")
// Output: <nil> DBG Hello World foo=bar // Output: <nil> DBG Hello World foo=bar
} }
func ExampleNewConsoleWriter_customFormatters() { func ExampleNewConsoleWriter_customFormatters() {
out := zerolog.NewConsoleWriter( out := zlog.NewConsoleWriter(
func(w *zerolog.ConsoleWriter) { func(w *zlog.ConsoleWriter) {
// Customize time format // Customize time format
w.TimeFormat = time.RFC822 w.TimeFormat = time.RFC822
// Customize level formatting // Customize level formatting
@ -50,7 +50,7 @@ func ExampleNewConsoleWriter_customFormatters() {
) )
out.NoColor = true // For testing purposes only out.NoColor = true // For testing purposes only
log := zerolog.New(out) log := zlog.New(out)
log.Info().Str("foo", "bar").Msg("Hello World") log.Info().Str("foo", "bar").Msg("Hello World")
// Output: <nil> [INFO ] Hello World foo=bar // Output: <nil> [INFO ] Hello World foo=bar
@ -59,7 +59,7 @@ func ExampleNewConsoleWriter_customFormatters() {
func TestConsoleLogger(t *testing.T) { func TestConsoleLogger(t *testing.T) {
t.Run("Numbers", func(t *testing.T) { t.Run("Numbers", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
log := zerolog.New(zerolog.ConsoleWriter{Out: buf, NoColor: true}) log := zlog.New(zlog.ConsoleWriter{Out: buf, NoColor: true})
log.Info(). log.Info().
Float64("float", 1.23). Float64("float", 1.23).
Uint64("small", 123). Uint64("small", 123).
@ -74,7 +74,7 @@ func TestConsoleLogger(t *testing.T) {
func TestConsoleWriter(t *testing.T) { func TestConsoleWriter(t *testing.T) {
t.Run("Default field formatter", func(t *testing.T) { t.Run("Default field formatter", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true, PartsOrder: []string{"foo"}} w := zlog.ConsoleWriter{Out: buf, NoColor: true, PartsOrder: []string{"foo"}}
_, err := w.Write([]byte(`{"foo": "DEFAULT"}`)) _, err := w.Write([]byte(`{"foo": "DEFAULT"}`))
if err != nil { if err != nil {
@ -90,7 +90,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write colorized", func(t *testing.T) { t.Run("Write colorized", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: false} w := zlog.ConsoleWriter{Out: buf, NoColor: false}
_, err := w.Write([]byte(`{"level": "warn", "message": "Foobar"}`)) _, err := w.Write([]byte(`{"level": "warn", "message": "Foobar"}`))
if err != nil { if err != nil {
@ -106,7 +106,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write fields", func(t *testing.T) { t.Run("Write fields", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true} w := zlog.ConsoleWriter{Out: buf, NoColor: true}
d := time.Unix(0, 0).UTC().Format(time.RFC3339) d := time.Unix(0, 0).UTC().Format(time.RFC3339)
_, err := w.Write([]byte(`{"time": "` + d + `", "level": "debug", "message": "Foobar", "foo": "bar"}`)) _, err := w.Write([]byte(`{"time": "` + d + `", "level": "debug", "message": "Foobar", "foo": "bar"}`))
@ -122,14 +122,14 @@ func TestConsoleWriter(t *testing.T) {
}) })
t.Run("Unix timestamp input format", func(t *testing.T) { t.Run("Unix timestamp input format", func(t *testing.T) {
of := zerolog.TimeFieldFormat of := zlog.TimeFieldFormat
defer func() { defer func() {
zerolog.TimeFieldFormat = of zlog.TimeFieldFormat = of
}() }()
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zlog.TimeFieldFormat = zlog.TimeFormatUnix
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.StampMilli, NoColor: true} w := zlog.ConsoleWriter{Out: buf, TimeFormat: time.StampMilli, NoColor: true}
_, err := w.Write([]byte(`{"time": 1234, "level": "debug", "message": "Foobar", "foo": "bar"}`)) _, err := w.Write([]byte(`{"time": 1234, "level": "debug", "message": "Foobar", "foo": "bar"}`))
if err != nil { if err != nil {
@ -144,14 +144,14 @@ func TestConsoleWriter(t *testing.T) {
}) })
t.Run("Unix timestamp ms input format", func(t *testing.T) { t.Run("Unix timestamp ms input format", func(t *testing.T) {
of := zerolog.TimeFieldFormat of := zlog.TimeFieldFormat
defer func() { defer func() {
zerolog.TimeFieldFormat = of zlog.TimeFieldFormat = of
}() }()
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs zlog.TimeFieldFormat = zlog.TimeFormatUnixMs
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.StampMilli, NoColor: true} w := zlog.ConsoleWriter{Out: buf, TimeFormat: time.StampMilli, NoColor: true}
_, err := w.Write([]byte(`{"time": 1234567, "level": "debug", "message": "Foobar", "foo": "bar"}`)) _, err := w.Write([]byte(`{"time": 1234567, "level": "debug", "message": "Foobar", "foo": "bar"}`))
if err != nil { if err != nil {
@ -166,14 +166,14 @@ func TestConsoleWriter(t *testing.T) {
}) })
t.Run("Unix timestamp us input format", func(t *testing.T) { t.Run("Unix timestamp us input format", func(t *testing.T) {
of := zerolog.TimeFieldFormat of := zlog.TimeFieldFormat
defer func() { defer func() {
zerolog.TimeFieldFormat = of zlog.TimeFieldFormat = of
}() }()
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMicro zlog.TimeFieldFormat = zlog.TimeFormatUnixMicro
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.StampMicro, NoColor: true} w := zlog.ConsoleWriter{Out: buf, TimeFormat: time.StampMicro, NoColor: true}
_, err := w.Write([]byte(`{"time": 1234567891, "level": "debug", "message": "Foobar", "foo": "bar"}`)) _, err := w.Write([]byte(`{"time": 1234567891, "level": "debug", "message": "Foobar", "foo": "bar"}`))
if err != nil { if err != nil {
@ -189,7 +189,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("No message field", func(t *testing.T) { t.Run("No message field", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true} w := zlog.ConsoleWriter{Out: buf, NoColor: true}
_, err := w.Write([]byte(`{"level": "debug", "foo": "bar"}`)) _, err := w.Write([]byte(`{"level": "debug", "foo": "bar"}`))
if err != nil { if err != nil {
@ -205,7 +205,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("No level field", func(t *testing.T) { t.Run("No level field", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true} w := zlog.ConsoleWriter{Out: buf, NoColor: true}
_, err := w.Write([]byte(`{"message": "Foobar", "foo": "bar"}`)) _, err := w.Write([]byte(`{"message": "Foobar", "foo": "bar"}`))
if err != nil { if err != nil {
@ -221,7 +221,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write colorized fields", func(t *testing.T) { t.Run("Write colorized fields", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: false} w := zlog.ConsoleWriter{Out: buf, NoColor: false}
_, err := w.Write([]byte(`{"level": "warn", "message": "Foobar", "foo": "bar"}`)) _, err := w.Write([]byte(`{"level": "warn", "message": "Foobar", "foo": "bar"}`))
if err != nil { if err != nil {
@ -237,7 +237,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write error field", func(t *testing.T) { t.Run("Write error field", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true} w := zlog.ConsoleWriter{Out: buf, NoColor: true}
d := time.Unix(0, 0).UTC().Format(time.RFC3339) d := time.Unix(0, 0).UTC().Format(time.RFC3339)
evt := `{"time": "` + d + `", "level": "error", "message": "Foobar", "aaa": "bbb", "error": "Error"}` evt := `{"time": "` + d + `", "level": "error", "message": "Foobar", "aaa": "bbb", "error": "Error"}`
@ -257,7 +257,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write caller field", func(t *testing.T) { t.Run("Write caller field", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true} w := zlog.ConsoleWriter{Out: buf, NoColor: true}
cwd, err := os.Getwd() cwd, err := os.Getwd()
if err != nil { if err != nil {
@ -282,7 +282,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write JSON field", func(t *testing.T) { t.Run("Write JSON field", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true} w := zlog.ConsoleWriter{Out: buf, NoColor: true}
evt := `{"level": "debug", "message": "Foobar", "foo": [1, 2, 3], "bar": true}` evt := `{"level": "debug", "message": "Foobar", "foo": [1, 2, 3], "bar": true}`
// t.Log(evt) // t.Log(evt)
@ -303,7 +303,7 @@ func TestConsoleWriter(t *testing.T) {
func TestConsoleWriterConfiguration(t *testing.T) { func TestConsoleWriterConfiguration(t *testing.T) {
t.Run("Sets TimeFormat", func(t *testing.T) { t.Run("Sets TimeFormat", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true, TimeFormat: time.RFC3339} w := zlog.ConsoleWriter{Out: buf, NoColor: true, TimeFormat: time.RFC3339}
d := time.Unix(0, 0).UTC().Format(time.RFC3339) d := time.Unix(0, 0).UTC().Format(time.RFC3339)
evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}` evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}`
@ -322,7 +322,7 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Run("Sets PartsOrder", func(t *testing.T) { t.Run("Sets PartsOrder", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true, PartsOrder: []string{"message", "level"}} w := zlog.ConsoleWriter{Out: buf, NoColor: true, PartsOrder: []string{"message", "level"}}
evt := `{"level": "info", "message": "Foobar"}` evt := `{"level": "info", "message": "Foobar"}`
_, err := w.Write([]byte(evt)) _, err := w.Write([]byte(evt))
@ -339,7 +339,7 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Run("Sets PartsExclude", func(t *testing.T) { t.Run("Sets PartsExclude", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true, PartsExclude: []string{"time"}} w := zlog.ConsoleWriter{Out: buf, NoColor: true, PartsExclude: []string{"time"}}
d := time.Unix(0, 0).UTC().Format(time.RFC3339) d := time.Unix(0, 0).UTC().Format(time.RFC3339)
evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}` evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}`
@ -357,7 +357,7 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Run("Sets FieldsExclude", func(t *testing.T) { t.Run("Sets FieldsExclude", func(t *testing.T) {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true, FieldsExclude: []string{"foo"}} w := zlog.ConsoleWriter{Out: buf, NoColor: true, FieldsExclude: []string{"foo"}}
evt := `{"level": "info", "message": "Foobar", "foo":"bar", "baz":"quux"}` evt := `{"level": "info", "message": "Foobar", "foo":"bar", "baz":"quux"}`
_, err := w.Write([]byte(evt)) _, err := w.Write([]byte(evt))
@ -379,7 +379,7 @@ func BenchmarkConsoleWriter(b *testing.B) {
var msg = []byte(`{"level": "info", "foo": "bar", "message": "HELLO", "time": "1990-01-01"}`) var msg = []byte(`{"level": "info", "foo": "bar", "message": "HELLO", "time": "1990-01-01"}`)
w := zerolog.ConsoleWriter{Out: ioutil.Discard, NoColor: false} w := zlog.ConsoleWriter{Out: ioutil.Discard, NoColor: false}
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
w.Write(msg) w.Write(msg)

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"fmt" "fmt"
@ -35,7 +35,7 @@ func (c Context) Dict(key string, dict *Event) Context {
} }
// Array adds the field key with an array to the event context. // Array adds the field key with an array to the event context.
// Use zerolog.Arr() to create the array or pass a type that // Use zlog.Arr() to create the array or pass a type that
// implement the LogArrayMarshaler interface. // implement the LogArrayMarshaler interface.
func (c Context) Array(key string, arr LogArrayMarshaler) Context { func (c Context) Array(key string, arr LogArrayMarshaler) Context {
c.l.context = enc.AppendKey(c.l.context, key) c.l.context = enc.AppendKey(c.l.context, key)
@ -330,7 +330,7 @@ func (ts timestampHook) Run(e *Event, level Level, msg string) {
var th = timestampHook{} var th = timestampHook{}
// Timestamp adds the current local time as UNIX timestamp to the logger context with the "time" key. // Timestamp adds the current local time as UNIX timestamp to the logger context with the "time" key.
// To customize the key name, change zerolog.TimestampFieldName. // To customize the key name, change zlog.TimestampFieldName.
// //
// NOTE: It won't dedupe the "time" key if the *Context has one already. // NOTE: It won't dedupe the "time" key if the *Context has one already.
func (c Context) Timestamp() Context { func (c Context) Timestamp() Context {
@ -338,13 +338,13 @@ func (c Context) Timestamp() Context {
return c return c
} }
// Time adds the field key with t formated as string using zerolog.TimeFieldFormat. // Time adds the field key with t formated as string using zlog.TimeFieldFormat.
func (c Context) Time(key string, t time.Time) Context { func (c Context) Time(key string, t time.Time) Context {
c.l.context = enc.AppendTime(enc.AppendKey(c.l.context, key), t, TimeFieldFormat) c.l.context = enc.AppendTime(enc.AppendKey(c.l.context, key), t, TimeFieldFormat)
return c return c
} }
// Times adds the field key with t formated as string using zerolog.TimeFieldFormat. // Times adds the field key with t formated as string using zlog.TimeFieldFormat.
func (c Context) Times(key string, t []time.Time) Context { func (c Context) Times(key string, t []time.Time) Context {
c.l.context = enc.AppendTimes(enc.AppendKey(c.l.context, key), t, TimeFieldFormat) c.l.context = enc.AppendTimes(enc.AppendKey(c.l.context, key), t, TimeFieldFormat)
return c return c
@ -394,13 +394,13 @@ const useGlobalSkipFrameCount = math.MinInt32
// ch is the default caller hook using the global CallerSkipFrameCount. // ch is the default caller hook using the global CallerSkipFrameCount.
var ch = newCallerHook(useGlobalSkipFrameCount) var ch = newCallerHook(useGlobalSkipFrameCount)
// Caller adds the file:line of the caller with the zerolog.CallerFieldName key. // Caller adds the file:line of the caller with the zlog.CallerFieldName key.
func (c Context) Caller() Context { func (c Context) Caller() Context {
c.l = c.l.Hook(ch) c.l = c.l.Hook(ch)
return c return c
} }
// CallerWithSkipFrameCount adds the file:line of the caller with the zerolog.CallerFieldName key. // CallerWithSkipFrameCount adds the file:line of the caller with the zlog.CallerFieldName key.
// The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger. // The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger.
// If set to -1 the global CallerSkipFrameCount will be used. // If set to -1 the global CallerSkipFrameCount will be used.
func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context { func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context {

4
ctx.go
View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"context" "context"
@ -21,7 +21,7 @@ type ctxKey struct{}
// notation: // notation:
// //
// ctx := r.Context() // ctx := r.Context()
// l := zerolog.Ctx(ctx) // l := zlog.Ctx(ctx)
// l.UpdateContext(func(c Context) Context { // l.UpdateContext(func(c Context) Context {
// return c.Str("bar", "baz") // return c.Str("bar", "baz")
// }) // })

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"context" "context"

View File

@ -8,7 +8,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/rs/zerolog/diode/internal/diodes" "git.tuxpa.in/a/zlog/diode/internal/diodes"
) )
var bufPool = &sync.Pool{ var bufPool = &sync.Pool{
@ -42,7 +42,7 @@ type Writer struct {
// wr := diode.NewWriter(w, 1000, 0, func(missed int) { // wr := diode.NewWriter(w, 1000, 0, func(missed int) {
// log.Printf("Dropped %d messages", missed) // log.Printf("Dropped %d messages", missed)
// }) // })
// log := zerolog.New(wr) // log := zlog.New(wr)
// //
// If pollInterval is greater than 0, a poller is used otherwise a waiter is // If pollInterval is greater than 0, a poller is used otherwise a waiter is
// used. // used.
@ -72,7 +72,7 @@ func NewWriter(w io.Writer, size int, pollInterval time.Duration, f Alerter) Wri
} }
func (dw Writer) Write(p []byte) (n int, err error) { func (dw Writer) Write(p []byte) (n int, err error) {
// p is pooled in zerolog so we can't hold it passed this call, hence the // p is pooled in zlog so we can't hold it passed this call, hence the
// copy. // copy.
p = append(bufPool.Get().([]byte), p...) p = append(bufPool.Get().([]byte), p...)
dw.d.Set(diodes.GenericDataType(&p)) dw.d.Set(diodes.GenericDataType(&p))

View File

@ -6,15 +6,15 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/diode" "git.tuxpa.in/a/zlog/diode"
) )
func ExampleNewWriter() { func ExampleNewWriter() {
w := diode.NewWriter(os.Stdout, 1000, 0, func(missed int) { w := diode.NewWriter(os.Stdout, 1000, 0, func(missed int) {
fmt.Printf("Dropped %d messages\n", missed) fmt.Printf("Dropped %d messages\n", missed)
}) })
log := zerolog.New(w) log := zlog.New(w)
log.Print("test") log.Print("test")
w.Close() w.Close()

View File

@ -9,9 +9,9 @@ import (
"testing" "testing"
"time" "time"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/diode" "git.tuxpa.in/a/zlog/diode"
"github.com/rs/zerolog/internal/cbor" "git.tuxpa.in/a/zlog/internal/cbor"
) )
func TestNewWriter(t *testing.T) { func TestNewWriter(t *testing.T) {
@ -19,7 +19,7 @@ func TestNewWriter(t *testing.T) {
w := diode.NewWriter(&buf, 1000, 0, func(missed int) { w := diode.NewWriter(&buf, 1000, 0, func(missed int) {
fmt.Printf("Dropped %d messages\n", missed) fmt.Printf("Dropped %d messages\n", missed)
}) })
log := zerolog.New(w) log := zlog.New(w)
log.Print("test") log.Print("test")
w.Close() w.Close()
@ -40,7 +40,7 @@ func Benchmark(b *testing.B) {
for name, interval := range benchs { for name, interval := range benchs {
b.Run(name, func(b *testing.B) { b.Run(name, func(b *testing.B) {
w := diode.NewWriter(ioutil.Discard, 100000, interval, nil) w := diode.NewWriter(ioutil.Discard, 100000, interval, nil)
log := zerolog.New(w) log := zlog.New(w)
defer w.Close() defer w.Close()
b.SetParallelism(1000) b.SetParallelism(1000)

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"net" "net"

View File

@ -1,11 +1,11 @@
// +build binary_log // +build binary_log
package zerolog package zlog
// This file contains bindings to do binary encoding. // This file contains bindings to do binary encoding.
import ( import (
"github.com/rs/zerolog/internal/cbor" "git.tuxpa.in/a/zlog/internal/cbor"
) )
var ( var (

View File

@ -1,12 +1,12 @@
// +build !binary_log // +build !binary_log
package zerolog package zlog
// encoder_json.go file contains bindings to generate // encoder_json.go file contains bindings to generate
// JSON encoded byte stream. // JSON encoded byte stream.
import ( import (
"github.com/rs/zerolog/internal/json" "git.tuxpa.in/a/zlog/internal/json"
) )
var ( var (

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"fmt" "fmt"
@ -150,7 +150,7 @@ func (e *Event) msg(msg string) {
if ErrorHandler != nil { if ErrorHandler != nil {
ErrorHandler(err) ErrorHandler(err)
} else { } else {
fmt.Fprintf(os.Stderr, "zerolog: could not write event: %v\n", err) fmt.Fprintf(os.Stderr, "zlog: could not write event: %v\n", err)
} }
} }
} }
@ -167,7 +167,7 @@ func (e *Event) Fields(fields interface{}) *Event {
} }
// Dict adds the field key with a dict to the event context. // Dict adds the field key with a dict to the event context.
// Use zerolog.Dict() to create the dictionary. // Use zlog.Dict() to create the dictionary.
func (e *Event) Dict(key string, dict *Event) *Event { func (e *Event) Dict(key string, dict *Event) *Event {
if e == nil { if e == nil {
return e return e
@ -186,7 +186,7 @@ func Dict() *Event {
} }
// Array adds the field key with an array to the event context. // Array adds the field key with an array to the event context.
// Use zerolog.Arr() to create the array or pass a type that // Use zlog.Arr() to create the array or pass a type that
// implement the LogArrayMarshaler interface. // implement the LogArrayMarshaler interface.
func (e *Event) Array(key string, arr LogArrayMarshaler) *Event { func (e *Event) Array(key string, arr LogArrayMarshaler) *Event {
if e == nil { if e == nil {
@ -368,11 +368,11 @@ func (e *Event) Errs(key string, errs []error) *Event {
// Err adds the field "error" with serialized err to the *Event context. // Err adds the field "error" with serialized err to the *Event context.
// If err is nil, no field is added. // If err is nil, no field is added.
// //
// To customize the key name, change zerolog.ErrorFieldName. // To customize the key name, change zlog.ErrorFieldName.
// //
// If Stack() has been called before and zerolog.ErrorStackMarshaler is defined, // If Stack() has been called before and zlog.ErrorStackMarshaler is defined,
// the err is passed to ErrorStackMarshaler and the result is appended to the // the err is passed to ErrorStackMarshaler and the result is appended to the
// zerolog.ErrorStackFieldName. // zlog.ErrorStackFieldName.
func (e *Event) Err(err error) *Event { func (e *Event) Err(err error) *Event {
if e == nil { if e == nil {
return e return e
@ -640,7 +640,7 @@ func (e *Event) Floats64(key string, f []float64) *Event {
} }
// Timestamp adds the current local time as UNIX timestamp to the *Event context with the "time" key. // Timestamp adds the current local time as UNIX timestamp to the *Event context with the "time" key.
// To customize the key name, change zerolog.TimestampFieldName. // To customize the key name, change zlog.TimestampFieldName.
// //
// NOTE: It won't dedupe the "time" key if the *Event (or *Context) has one // NOTE: It won't dedupe the "time" key if the *Event (or *Context) has one
// already. // already.
@ -652,7 +652,7 @@ func (e *Event) Timestamp() *Event {
return e return e
} }
// Time adds the field key with t formatted as string using zerolog.TimeFieldFormat. // Time adds the field key with t formatted as string using zlog.TimeFieldFormat.
func (e *Event) Time(key string, t time.Time) *Event { func (e *Event) Time(key string, t time.Time) *Event {
if e == nil { if e == nil {
return e return e
@ -661,7 +661,7 @@ func (e *Event) Time(key string, t time.Time) *Event {
return e return e
} }
// Times adds the field key with t formatted as string using zerolog.TimeFieldFormat. // Times adds the field key with t formatted as string using zlog.TimeFieldFormat.
func (e *Event) Times(key string, t []time.Time) *Event { func (e *Event) Times(key string, t []time.Time) *Event {
if e == nil { if e == nil {
return e return e
@ -670,8 +670,8 @@ func (e *Event) Times(key string, t []time.Time) *Event {
return e return e
} }
// Dur adds the field key with duration d stored as zerolog.DurationFieldUnit. // Dur adds the field key with duration d stored as zlog.DurationFieldUnit.
// If zerolog.DurationFieldInteger is true, durations are rendered as integer // If zlog.DurationFieldInteger is true, durations are rendered as integer
// instead of float. // instead of float.
func (e *Event) Dur(key string, d time.Duration) *Event { func (e *Event) Dur(key string, d time.Duration) *Event {
if e == nil { if e == nil {
@ -681,8 +681,8 @@ func (e *Event) Dur(key string, d time.Duration) *Event {
return e return e
} }
// Durs adds the field key with duration d stored as zerolog.DurationFieldUnit. // Durs adds the field key with duration d stored as zlog.DurationFieldUnit.
// If zerolog.DurationFieldInteger is true, durations are rendered as integer // If zlog.DurationFieldInteger is true, durations are rendered as integer
// instead of float. // instead of float.
func (e *Event) Durs(key string, d []time.Duration) *Event { func (e *Event) Durs(key string, d []time.Duration) *Event {
if e == nil { if e == nil {
@ -729,7 +729,7 @@ func (e *Event) CallerSkipFrame(skip int) *Event {
return e return e
} }
// Caller adds the file:line of the caller with the zerolog.CallerFieldName key. // Caller adds the file:line of the caller with the zlog.CallerFieldName key.
// The argument skip is the number of stack frames to ascend // The argument skip is the number of stack frames to ascend
// Skip If not passed, use the global variable CallerSkipFrameCount // Skip If not passed, use the global variable CallerSkipFrameCount
func (e *Event) Caller(skip ...int) *Event { func (e *Event) Caller(skip ...int) *Event {

View File

@ -1,6 +1,6 @@
// +build !binary_log // +build !binary_log
package zerolog package zlog
import ( import (
"bytes" "bytes"

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"encoding/json" "encoding/json"

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"encoding/json" "encoding/json"
@ -96,7 +96,7 @@ var (
// set to true. // set to true.
DurationFieldInteger = false DurationFieldInteger = false
// ErrorHandler is called whenever zerolog fails to write an event on its // ErrorHandler is called whenever zlog fails to write an event on its
// output. If not set, an error is printed on the stderr. This handler must // output. If not set, an error is printed on the stderr. This handler must
// be thread safe and non-blocking. // be thread safe and non-blocking.
ErrorHandler func(err error) ErrorHandler func(err error)

2
go.mod
View File

@ -1,4 +1,4 @@
module github.com/rs/zerolog module git.tuxpa.in/a/zlog
go 1.15 go 1.15

View File

@ -1,6 +1,6 @@
// +build go1.12 // +build go1.12
package zerolog package zlog
// Since go 1.12, some auto generated init functions are hidden from // Since go 1.12, some auto generated init functions are hidden from
// runtime.Caller. // runtime.Caller.

View File

@ -1,4 +1,4 @@
// Package hlog provides a set of http.Handler helpers for zerolog. // Package hlog provides a set of http.Handler helpers for zlog.
package hlog package hlog
import ( import (
@ -7,19 +7,19 @@ import (
"time" "time"
"github.com/rs/xid" "github.com/rs/xid"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/hlog/internal/mutil" "git.tuxpa.in/a/zlog/hlog/internal/mutil"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
// FromRequest gets the logger in the request's context. // FromRequest gets the logger in the request's context.
// This is a shortcut for log.Ctx(r.Context()) // This is a shortcut for log.Ctx(r.Context())
func FromRequest(r *http.Request) *zerolog.Logger { func FromRequest(r *http.Request) *zlog.Logger {
return log.Ctx(r.Context()) return log.Ctx(r.Context())
} }
// NewHandler injects log into requests context. // NewHandler injects log into requests context.
func NewHandler(log zerolog.Logger) func(http.Handler) http.Handler { func NewHandler(log zlog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Create a copy of the logger (including internal context slice) // Create a copy of the logger (including internal context slice)
@ -36,8 +36,8 @@ func NewHandler(log zerolog.Logger) func(http.Handler) http.Handler {
func URLHandler(fieldKey string) func(next http.Handler) http.Handler { func URLHandler(fieldKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := zerolog.Ctx(r.Context()) log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context { log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, r.URL.String()) return c.Str(fieldKey, r.URL.String())
}) })
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
@ -50,8 +50,8 @@ func URLHandler(fieldKey string) func(next http.Handler) http.Handler {
func MethodHandler(fieldKey string) func(next http.Handler) http.Handler { func MethodHandler(fieldKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := zerolog.Ctx(r.Context()) log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context { log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, r.Method) return c.Str(fieldKey, r.Method)
}) })
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
@ -64,8 +64,8 @@ func MethodHandler(fieldKey string) func(next http.Handler) http.Handler {
func RequestHandler(fieldKey string) func(next http.Handler) http.Handler { func RequestHandler(fieldKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := zerolog.Ctx(r.Context()) log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context { log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, r.Method+" "+r.URL.String()) return c.Str(fieldKey, r.Method+" "+r.URL.String())
}) })
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
@ -79,8 +79,8 @@ func RemoteAddrHandler(fieldKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RemoteAddr != "" { if r.RemoteAddr != "" {
log := zerolog.Ctx(r.Context()) log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context { log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, r.RemoteAddr) return c.Str(fieldKey, r.RemoteAddr)
}) })
} }
@ -95,8 +95,8 @@ func UserAgentHandler(fieldKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ua := r.Header.Get("User-Agent"); ua != "" { if ua := r.Header.Get("User-Agent"); ua != "" {
log := zerolog.Ctx(r.Context()) log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context { log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, ua) return c.Str(fieldKey, ua)
}) })
} }
@ -111,8 +111,8 @@ func RefererHandler(fieldKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ref := r.Header.Get("Referer"); ref != "" { if ref := r.Header.Get("Referer"); ref != "" {
log := zerolog.Ctx(r.Context()) log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context { log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, ref) return c.Str(fieldKey, ref)
}) })
} }
@ -162,8 +162,8 @@ func RequestIDHandler(fieldKey, headerName string) func(next http.Handler) http.
r = r.WithContext(ctx) r = r.WithContext(ctx)
} }
if fieldKey != "" { if fieldKey != "" {
log := zerolog.Ctx(ctx) log := zlog.Ctx(ctx)
log.UpdateContext(func(c zerolog.Context) zerolog.Context { log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, id.String()) return c.Str(fieldKey, id.String())
}) })
} }
@ -181,8 +181,8 @@ func CustomHeaderHandler(fieldKey, header string) func(next http.Handler) http.H
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if val := r.Header.Get(header); val != "" { if val := r.Header.Get(header); val != "" {
log := zerolog.Ctx(r.Context()) log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context { log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, val) return c.Str(fieldKey, val)
}) })
} }

View File

@ -9,8 +9,8 @@ import (
"net/http/httptest" "net/http/httptest"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/hlog" "git.tuxpa.in/a/zlog/hlog"
) )
// fake alice to avoid dep // fake alice to avoid dep
@ -31,13 +31,13 @@ func (a alice) Then(h http.Handler) http.Handler {
} }
func init() { func init() {
zerolog.TimestampFunc = func() time.Time { zlog.TimestampFunc = func() time.Time {
return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC) return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC)
} }
} }
func Example_handler() { func Example_handler() {
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Timestamp(). Timestamp().
Str("role", "my-service"). Str("role", "my-service").
Str("host", "local-hostname"). Str("host", "local-hostname").

View File

@ -14,8 +14,8 @@ import (
"testing" "testing"
"github.com/rs/xid" "github.com/rs/xid"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/internal/cbor" "git.tuxpa.in/a/zlog/internal/cbor"
) )
func decodeIfBinary(out *bytes.Buffer) string { func decodeIfBinary(out *bytes.Buffer) string {
@ -27,7 +27,7 @@ func decodeIfBinary(out *bytes.Buffer) string {
} }
func TestNewHandler(t *testing.T) { func TestNewHandler(t *testing.T) {
log := zerolog.New(nil).With(). log := zlog.New(nil).With().
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
lh := NewHandler(log) lh := NewHandler(log)
@ -49,7 +49,7 @@ func TestURLHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"url":"/path?foo=bar"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"url":"/path?foo=bar"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -65,7 +65,7 @@ func TestMethodHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"method":"POST"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"method":"POST"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -82,7 +82,7 @@ func TestRequestHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"request":"POST /path?foo=bar"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"request":"POST /path?foo=bar"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -98,7 +98,7 @@ func TestRemoteAddrHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"ip":"1.2.3.4:1234"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"ip":"1.2.3.4:1234"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -114,7 +114,7 @@ func TestRemoteAddrHandlerIPv6(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"ip":"[2001:db8:a0b:12f0::1]:1234"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"ip":"[2001:db8:a0b:12f0::1]:1234"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -132,7 +132,7 @@ func TestUserAgentHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"ua":"some user agent string"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"ua":"some user agent string"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -150,7 +150,7 @@ func TestRefererHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"referer":"http://foo.com/bar"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"referer":"http://foo.com/bar"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -178,7 +178,7 @@ func TestRequestIDHandler(t *testing.T) {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
} }
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(httptest.NewRecorder(), r) h.ServeHTTP(httptest.NewRecorder(), r)
} }
@ -193,7 +193,7 @@ func TestCustomHeaderHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"reqID":"514bbe5bb5251c92bd07a9846f4a1ab6"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"reqID":"514bbe5bb5251c92bd07a9846f4a1ab6"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -210,7 +210,7 @@ func TestCombinedHandlers(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})))) }))))
h = NewHandler(zerolog.New(out))(h) h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r) h.ServeHTTP(nil, r)
if want, got := `{"method":"POST","request":"POST /path?foo=bar","url":"/path?foo=bar"}`+"\n", decodeIfBinary(out); want != got { if want, got := `{"method":"POST","request":"POST /path?foo=bar","url":"/path?foo=bar"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want) t.Errorf("Invalid log output, got: %s, want: %s", got, want)
@ -228,10 +228,10 @@ func BenchmarkHandlers(b *testing.B) {
})) }))
h2 := MethodHandler("method")(RequestHandler("request")(h1)) h2 := MethodHandler("method")(RequestHandler("request")(h1))
handlers := map[string]http.Handler{ handlers := map[string]http.Handler{
"Single": NewHandler(zerolog.New(ioutil.Discard))(h1), "Single": NewHandler(zlog.New(ioutil.Discard))(h1),
"Combined": NewHandler(zerolog.New(ioutil.Discard))(h2), "Combined": NewHandler(zlog.New(ioutil.Discard))(h2),
"SingleDisabled": NewHandler(zerolog.New(ioutil.Discard).Level(zerolog.Disabled))(h1), "SingleDisabled": NewHandler(zlog.New(ioutil.Discard).Level(zlog.Disabled))(h1),
"CombinedDisabled": NewHandler(zerolog.New(ioutil.Discard).Level(zerolog.Disabled))(h2), "CombinedDisabled": NewHandler(zlog.New(ioutil.Discard).Level(zlog.Disabled))(h2),
} }
for name := range handlers { for name := range handlers {
h := handlers[name] h := handlers[name]
@ -244,13 +244,13 @@ func BenchmarkHandlers(b *testing.B) {
} }
func BenchmarkDataRace(b *testing.B) { func BenchmarkDataRace(b *testing.B) {
log := zerolog.New(nil).With(). log := zlog.New(nil).With().
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
lh := NewHandler(log) lh := NewHandler(log)
h := lh(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := lh(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
l := FromRequest(r) l := FromRequest(r)
l.UpdateContext(func(c zerolog.Context) zerolog.Context { l.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str("bar", "baz") return c.Str("bar", "baz")
}) })
l.Log().Msg("") l.Log().Msg("")

View File

@ -1,4 +1,4 @@
package zerolog package zlog
// Hook defines an interface to a log hook. // Hook defines an interface to a log hook.
type Hook interface { type Hook interface {

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"bytes" "bytes"

View File

@ -8,7 +8,7 @@ import (
"os" "os"
"time" "time"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
) )
func writeLog(fname string, count int, useCompress bool) { func writeLog(fname string, count int, useCompress bool) {
@ -34,8 +34,8 @@ func writeLog(fname string, count int, useCompress bool) {
} }
zerolog.TimestampFunc = func() time.Time { return time.Now().Round(time.Second) } zlog.TimestampFunc = func() time.Time { return time.Now().Round(time.Second) }
log := zerolog.New(f).With(). log := zlog.New(f).With().
Timestamp(). Timestamp().
Logger() Logger()
for i := 0; i < count; i++ { for i := 0; i < count; i++ {

View File

@ -6,7 +6,7 @@ import (
) )
const ( const (
// Import from zerolog/global.go // Import from zlog/global.go
timeFormatUnix = "" timeFormatUnix = ""
timeFormatUnixMs = "UNIXMS" timeFormatUnixMs = "UNIXMS"
timeFormatUnixMicro = "UNIXMICRO" timeFormatUnixMicro = "UNIXMICRO"

View File

@ -6,8 +6,8 @@
package journald package journald
// This file provides a zerolog writer so that logs printed // This file provides a zlog writer so that logs printed
// using zerolog library can be sent to a journalD. // using zlog library can be sent to a journalD.
// Zerolog's Top level key/Value Pairs are translated to // Zerolog's Top level key/Value Pairs are translated to
// journald's args - all Values are sent to journald as strings. // journald's args - all Values are sent to journald as strings.
@ -25,13 +25,13 @@ import (
"strings" "strings"
"github.com/coreos/go-systemd/v22/journal" "github.com/coreos/go-systemd/v22/journal"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/internal/cbor" "git.tuxpa.in/a/zlog/internal/cbor"
) )
const defaultJournalDPrio = journal.PriNotice const defaultJournalDPrio = journal.PriNotice
// NewJournalDWriter returns a zerolog log destination // NewJournalDWriter returns a zlog log destination
// to be used as parameter to New() calls. Writing logs // to be used as parameter to New() calls. Writing logs
// to this writer will send the log messages to journalD // to this writer will send the log messages to journalD
// running in this system. // running in this system.
@ -42,28 +42,28 @@ func NewJournalDWriter() io.Writer {
type journalWriter struct { type journalWriter struct {
} }
// levelToJPrio converts zerolog Level string into // levelToJPrio converts zlog Level string into
// journalD's priority values. JournalD has more // journalD's priority values. JournalD has more
// priorities than zerolog. // priorities than zlog.
func levelToJPrio(zLevel string) journal.Priority { func levelToJPrio(zLevel string) journal.Priority {
lvl, _ := zerolog.ParseLevel(zLevel) lvl, _ := zlog.ParseLevel(zLevel)
switch lvl { switch lvl {
case zerolog.TraceLevel: case zlog.TraceLevel:
return journal.PriDebug return journal.PriDebug
case zerolog.DebugLevel: case zlog.DebugLevel:
return journal.PriDebug return journal.PriDebug
case zerolog.InfoLevel: case zlog.InfoLevel:
return journal.PriInfo return journal.PriInfo
case zerolog.WarnLevel: case zlog.WarnLevel:
return journal.PriWarning return journal.PriWarning
case zerolog.ErrorLevel: case zlog.ErrorLevel:
return journal.PriErr return journal.PriErr
case zerolog.FatalLevel: case zlog.FatalLevel:
return journal.PriCrit return journal.PriCrit
case zerolog.PanicLevel: case zlog.PanicLevel:
return journal.PriEmerg return journal.PriEmerg
case zerolog.NoLevel: case zlog.NoLevel:
return journal.PriNotice return journal.PriNotice
} }
return defaultJournalDPrio return defaultJournalDPrio
@ -81,7 +81,7 @@ func (w journalWriter) Write(p []byte) (n int, err error) {
if err != nil { if err != nil {
return return
} }
if l, ok := event[zerolog.LevelFieldName].(string); ok { if l, ok := event[zlog.LevelFieldName].(string); ok {
jPrio = levelToJPrio(l) jPrio = levelToJPrio(l)
} }
@ -89,9 +89,9 @@ func (w journalWriter) Write(p []byte) (n int, err error) {
for key, value := range event { for key, value := range event {
jKey := strings.ToUpper(key) jKey := strings.ToUpper(key)
switch key { switch key {
case zerolog.LevelFieldName, zerolog.TimestampFieldName: case zlog.LevelFieldName, zlog.TimestampFieldName:
continue continue
case zerolog.MessageFieldName: case zlog.MessageFieldName:
msg, _ = value.(string) msg, _ = value.(string)
continue continue
} }

View File

@ -7,12 +7,12 @@ import (
"io" "io"
"testing" "testing"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/journald" "git.tuxpa.in/a/zlog/journald"
) )
func ExampleNewJournalDWriter() { func ExampleNewJournalDWriter() {
log := zerolog.New(journald.NewJournalDWriter()) log := zlog.New(journald.NewJournalDWriter())
log.Info().Str("foo", "bar").Uint64("small", 123).Float64("float", 3.14).Uint64("big", 1152921504606846976).Msg("Journal Test") log.Info().Str("foo", "bar").Uint64("small", 123).Float64("float", 3.14).Uint64("big", 1152921504606846976).Msg("Journal Test")
// Output: // Output:
} }
@ -71,14 +71,14 @@ func TestMultiWrite(t *testing.T) {
w3 = journald.NewJournalDWriter() w3 = journald.NewJournalDWriter()
) )
zerolog.ErrorHandler = func(err error) { zlog.ErrorHandler = func(err error) {
if err == io.ErrShortWrite { if err == io.ErrShortWrite {
t.Errorf("Unexpected ShortWriteError") t.Errorf("Unexpected ShortWriteError")
t.FailNow() t.FailNow()
} }
} }
log := zerolog.New(io.MultiWriter(w1, w2, w3)).With().Logger() log := zlog.New(io.MultiWriter(w1, w2, w3)).With().Logger()
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
log.Info().Msg("Tick!") log.Info().Msg("Tick!")

24
log.go
View File

@ -1,13 +1,13 @@
// Package zerolog provides a lightweight logging library dedicated to JSON logging. // Package zlog provides a lightweight logging library dedicated to JSON logging.
// //
// A global Logger can be use for simple logging: // A global Logger can be use for simple logging:
// //
// import "github.com/rs/zerolog/log" // import "git.tuxpa.in/a/zlog/log"
// //
// log.Info().Msg("hello world") // log.Info().Msg("hello world")
// // Output: {"time":1494567715,"level":"info","message":"hello world"} // // Output: {"time":1494567715,"level":"info","message":"hello world"}
// //
// NOTE: To import the global logger, import the "log" subpackage "github.com/rs/zerolog/log". // NOTE: To import the global logger, import the "log" subpackage "git.tuxpa.in/a/zlog/log".
// //
// Fields can be added to log messages: // Fields can be added to log messages:
// //
@ -16,7 +16,7 @@
// //
// Create logger instance to manage different outputs: // Create logger instance to manage different outputs:
// //
// logger := zerolog.New(os.Stderr).With().Timestamp().Logger() // logger := zlog.New(os.Stderr).With().Timestamp().Logger()
// logger.Info(). // logger.Info().
// Str("foo", "bar"). // Str("foo", "bar").
// Msg("hello world") // Msg("hello world")
@ -30,7 +30,7 @@
// //
// Level logging // Level logging
// //
// zerolog.SetGlobalLevel(zerolog.InfoLevel) // zlog.SetGlobalLevel(zlog.InfoLevel)
// //
// log.Debug().Msg("filtered out message") // log.Debug().Msg("filtered out message")
// log.Info().Msg("routed message") // log.Info().Msg("routed message")
@ -62,7 +62,7 @@
// //
// Sample logs: // Sample logs:
// //
// sampled := log.Sample(&zerolog.BasicSampler{N: 10}) // sampled := log.Sample(&zlog.BasicSampler{N: 10})
// sampled.Info().Msg("will be logged every 10 messages") // sampled.Info().Msg("will be logged every 10 messages")
// //
// Log with contextual hooks: // Log with contextual hooks:
@ -70,15 +70,15 @@
// // Create the hook: // // Create the hook:
// type SeverityHook struct{} // type SeverityHook struct{}
// //
// func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) { // func (h SeverityHook) Run(e *zlog.Event, level zlog.Level, msg string) {
// if level != zerolog.NoLevel { // if level != zlog.NoLevel {
// e.Str("severity", level.String()) // e.Str("severity", level.String())
// } // }
// } // }
// //
// // And use it: // // And use it:
// var h SeverityHook // var h SeverityHook
// log := zerolog.New(os.Stdout).Hook(h) // log := zlog.New(os.Stdout).Hook(h)
// log.Warn().Msg("") // log.Warn().Msg("")
// // Output: {"level":"warn","severity":"warn"} // // Output: {"level":"warn","severity":"warn"}
// //
@ -88,7 +88,7 @@
// There is no fields deduplication out-of-the-box. // There is no fields deduplication out-of-the-box.
// Using the same key multiple times creates new key in final JSON each time. // Using the same key multiple times creates new key in final JSON each time.
// //
// logger := zerolog.New(os.Stderr).With().Timestamp().Logger() // logger := zlog.New(os.Stderr).With().Timestamp().Logger()
// logger.Info(). // logger.Info().
// Timestamp(). // Timestamp().
// Msg("dup") // Msg("dup")
@ -96,7 +96,7 @@
// //
// In this case, many consumers will take the last value, // In this case, many consumers will take the last value,
// but this is not guaranteed; check yours if in doubt. // but this is not guaranteed; check yours if in doubt.
package zerolog package zlog
import ( import (
"fmt" "fmt"
@ -156,7 +156,7 @@ func (l Level) String() string {
return strconv.Itoa(int(l)) return strconv.Itoa(int(l))
} }
// ParseLevel converts a level string into a zerolog Level value. // ParseLevel converts a level string into a zlog Level value.
// returns an error if the input string does not match known values. // returns an error if the input string does not match known values.
func ParseLevel(levelStr string) (Level, error) { func ParseLevel(levelStr string) (Level, error) {
switch levelStr { switch levelStr {

View File

@ -1,4 +1,4 @@
// Package log provides a global logger for zerolog. // Package log provides a global logger for zlog.
package log package log
import ( import (
@ -6,35 +6,40 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"time"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
) )
// Logger is the global logger. // Logger is the global logger.
var Logger = zerolog.New(os.Stderr).With().Timestamp().Logger() var Logger = zlog.New(os.Stderr).With().Timestamp().Logger()
func init() {
zlog.TimeFieldFormat = time.RFC3339Nano
}
// Output duplicates the global logger and sets w as its output. // Output duplicates the global logger and sets w as its output.
func Output(w io.Writer) zerolog.Logger { func Output(w io.Writer) zlog.Logger {
return Logger.Output(w) return Logger.Output(w)
} }
// With creates a child logger with the field added to its context. // With creates a child logger with the field added to its context.
func With() zerolog.Context { func With() zlog.Context {
return Logger.With() return Logger.With()
} }
// Level creates a child logger with the minimum accepted level set to level. // Level creates a child logger with the minimum accepted level set to level.
func Level(level zerolog.Level) zerolog.Logger { func Level(level zlog.Level) zlog.Logger {
return Logger.Level(level) return Logger.Level(level)
} }
// Sample returns a logger with the s sampler. // Sample returns a logger with the s sampler.
func Sample(s zerolog.Sampler) zerolog.Logger { func Sample(s zlog.Sampler) zlog.Logger {
return Logger.Sample(s) return Logger.Sample(s)
} }
// Hook returns a logger with the h Hook. // Hook returns a logger with the h Hook.
func Hook(h zerolog.Hook) zerolog.Logger { func Hook(h zlog.Hook) zlog.Logger {
return Logger.Hook(h) return Logger.Hook(h)
} }
@ -42,73 +47,99 @@ func Hook(h zerolog.Hook) zerolog.Logger {
// with info level if err is nil. // with info level if err is nil.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Err(err error) *zerolog.Event { func Err(err error) *zlog.Event {
return Logger.Err(err) return Logger.Err(err)
} }
// Trace starts a new message with trace level. // Trace starts a new message with trace level.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Trace() *zerolog.Event { func Trace() *zlog.Event {
return Logger.Trace() return Logger.Trace()
} }
// Debug starts a new message with debug level. // Debug starts a new message with debug level.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Debug() *zerolog.Event { func Debug() *zlog.Event {
return Logger.Debug() return Logger.Debug()
} }
// Info starts a new message with info level. // Info starts a new message with info level.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Info() *zerolog.Event { func Info() *zlog.Event {
return Logger.Info() return Logger.Info()
} }
// Warn starts a new message with warn level. // Warn starts a new message with warn level.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Warn() *zerolog.Event { func Warn() *zlog.Event {
return Logger.Warn() return Logger.Warn()
} }
// Error starts a new message with error level. // Error starts a new message with error level.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Error() *zerolog.Event { func Error() *zlog.Event {
return Logger.Error() return Logger.Error()
} }
// Errorf sends a log event using debug level and no extra field.
// Arguments are handled in the manner of fmt.Errorf.
func Errorf(format string, v ...interface{}) {
Logger.Error().CallerSkipFrame(1).Msgf(format, v...)
}
func Errorln(args ...interface{}) {
Logger.Error().Msg(fmt.Sprintln(args...))
}
// Fatal starts a new message with fatal level. The os.Exit(1) function // Fatal starts a new message with fatal level. The os.Exit(1) function
// is called by the Msg method. // is called by the Msg method.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Fatal() *zerolog.Event { func Fatal() *zlog.Event {
return Logger.Fatal() return Logger.Fatal()
} }
func Fatalf(format string, args ...interface{}) {
Logger.Fatal().Msgf(format, args)
}
func Fatalln(args ...interface{}) {
Logger.Fatal().Msg(fmt.Sprintln(args...))
}
// Panic starts a new message with panic level. The message is also sent // Panic starts a new message with panic level. The message is also sent
// to the panic function. // to the panic function.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Panic() *zerolog.Event { func Panic() *zlog.Event {
return Logger.Panic() return Logger.Panic()
} }
func Panicf(format string, args ...interface{}) {
Logger.Panic().Msgf(format, args)
}
func Panicln(args ...interface{}) {
Logger.Panic().Msg(fmt.Sprintln(args...))
}
// WithLevel starts a new message with level. // WithLevel starts a new message with level.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func WithLevel(level zerolog.Level) *zerolog.Event { func WithLevel(level zlog.Level) *zlog.Event {
return Logger.WithLevel(level) return Logger.WithLevel(level)
} }
// Log starts a new message with no level. Setting zerolog.GlobalLevel to // Log starts a new message with no level. Setting zlog.GlobalLevel to
// zerolog.Disabled will still disable events produced by this method. // zlog.Disabled will still disable events produced by this method.
// //
// You must call Msg on the returned event in order to send the event. // You must call Msg on the returned event in order to send the event.
func Log() *zerolog.Event { func Log() *zlog.Event {
return Logger.Log() return Logger.Log()
} }
@ -124,8 +155,12 @@ func Printf(format string, v ...interface{}) {
Logger.Debug().CallerSkipFrame(1).Msgf(format, v...) Logger.Debug().CallerSkipFrame(1).Msgf(format, v...)
} }
func Println(args ...interface{}) {
Logger.Debug().Msg(fmt.Sprintln(args...))
}
// Ctx returns the Logger associated with the ctx. If no logger // Ctx returns the Logger associated with the ctx. If no logger
// is associated, a disabled logger is returned. // is associated, a disabled logger is returned.
func Ctx(ctx context.Context) *zerolog.Logger { func Ctx(ctx context.Context) *zlog.Logger {
return zerolog.Ctx(ctx) return zlog.Ctx(ctx)
} }

View File

@ -1,3 +1,4 @@
//go:build !binary_log
// +build !binary_log // +build !binary_log
package log_test package log_test
@ -8,8 +9,8 @@ import (
"os" "os"
"time" "time"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
"github.com/rs/zerolog/log" "git.tuxpa.in/a/zlog/log"
) )
// setup would normally be an init() function, however, there seems // setup would normally be an init() function, however, there seems
@ -17,16 +18,16 @@ import (
// global Logger from an init() // global Logger from an init()
func setup() { func setup() {
// UNIX Time is faster and smaller than most timestamps // UNIX Time is faster and smaller than most timestamps
// If you set zerolog.TimeFieldFormat to an empty string, // If you set zlog.TimeFieldFormat to an empty string,
// logs will write with UNIX time // logs will write with UNIX time
zerolog.TimeFieldFormat = "" zlog.TimeFieldFormat = ""
// In order to always output a static time to stdout for these // In order to always output a static time to stdout for these
// examples to pass, we need to override zerolog.TimestampFunc // examples to pass, we need to override zlog.TimestampFunc
// and log.Logger globals -- you would not normally need to do this // and log.Logger globals -- you would not normally need to do this
zerolog.TimestampFunc = func() time.Time { zlog.TimestampFunc = func() time.Time {
return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC) return time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)
} }
log.Logger = zerolog.New(os.Stdout).With().Timestamp().Logger() log.Logger = zlog.New(os.Stdout).With().Timestamp().Logger()
} }
// Simple logging example using the Print function in the log package // Simple logging example using the Print function in the log package
@ -130,9 +131,9 @@ func Example() {
flag.Parse() flag.Parse()
// Default level for this example is info, unless debug flag is present // Default level for this example is info, unless debug flag is present
zerolog.SetGlobalLevel(zerolog.InfoLevel) zlog.SetGlobalLevel(zlog.InfoLevel)
if *debug { if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel) zlog.SetGlobalLevel(zlog.DebugLevel)
} }
log.Debug().Msg("This message appears only when log level set to Debug") log.Debug().Msg("This message appears only when log level set to Debug")

View File

@ -1,6 +1,6 @@
// +build !binary_log // +build !binary_log
package zerolog_test package zlog_test
import ( import (
"errors" "errors"
@ -10,18 +10,18 @@ import (
"os" "os"
"time" "time"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
) )
func ExampleNew() { func ExampleNew() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Info().Msg("hello world") log.Info().Msg("hello world")
// Output: {"level":"info","message":"hello world"} // Output: {"level":"info","message":"hello world"}
} }
func ExampleLogger_With() { func ExampleLogger_With() {
log := zerolog.New(os.Stdout). log := zlog.New(os.Stdout).
With(). With().
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
@ -32,7 +32,7 @@ func ExampleLogger_With() {
} }
func ExampleLogger_Level() { func ExampleLogger_Level() {
log := zerolog.New(os.Stdout).Level(zerolog.WarnLevel) log := zlog.New(os.Stdout).Level(zlog.WarnLevel)
log.Info().Msg("filtered out message") log.Info().Msg("filtered out message")
log.Error().Msg("kept message") log.Error().Msg("kept message")
@ -41,7 +41,7 @@ func ExampleLogger_Level() {
} }
func ExampleLogger_Sample() { func ExampleLogger_Sample() {
log := zerolog.New(os.Stdout).Sample(&zerolog.BasicSampler{N: 2}) log := zlog.New(os.Stdout).Sample(&zlog.BasicSampler{N: 2})
log.Info().Msg("message 1") log.Info().Msg("message 1")
log.Info().Msg("message 2") log.Info().Msg("message 2")
@ -54,8 +54,8 @@ func ExampleLogger_Sample() {
type LevelNameHook struct{} type LevelNameHook struct{}
func (h LevelNameHook) Run(e *zerolog.Event, l zerolog.Level, msg string) { func (h LevelNameHook) Run(e *zlog.Event, l zlog.Level, msg string) {
if l != zerolog.NoLevel { if l != zlog.NoLevel {
e.Str("level_name", l.String()) e.Str("level_name", l.String())
} else { } else {
e.Str("level_name", "NoLevel") e.Str("level_name", "NoLevel")
@ -64,7 +64,7 @@ func (h LevelNameHook) Run(e *zerolog.Event, l zerolog.Level, msg string) {
type MessageHook string type MessageHook string
func (h MessageHook) Run(e *zerolog.Event, l zerolog.Level, msg string) { func (h MessageHook) Run(e *zlog.Event, l zlog.Level, msg string) {
e.Str("the_message", msg) e.Str("the_message", msg)
} }
@ -72,7 +72,7 @@ func ExampleLogger_Hook() {
var levelNameHook LevelNameHook var levelNameHook LevelNameHook
var messageHook MessageHook = "The message" var messageHook MessageHook = "The message"
log := zerolog.New(os.Stdout).Hook(levelNameHook).Hook(messageHook) log := zlog.New(os.Stdout).Hook(levelNameHook).Hook(messageHook)
log.Info().Msg("hello world") log.Info().Msg("hello world")
@ -80,7 +80,7 @@ func ExampleLogger_Hook() {
} }
func ExampleLogger_Print() { func ExampleLogger_Print() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Print("hello world") log.Print("hello world")
@ -88,7 +88,7 @@ func ExampleLogger_Print() {
} }
func ExampleLogger_Printf() { func ExampleLogger_Printf() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Printf("hello %s", "world") log.Printf("hello %s", "world")
@ -96,7 +96,7 @@ func ExampleLogger_Printf() {
} }
func ExampleLogger_Trace() { func ExampleLogger_Trace() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Trace(). log.Trace().
Str("foo", "bar"). Str("foo", "bar").
@ -107,7 +107,7 @@ func ExampleLogger_Trace() {
} }
func ExampleLogger_Debug() { func ExampleLogger_Debug() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Debug(). log.Debug().
Str("foo", "bar"). Str("foo", "bar").
@ -118,7 +118,7 @@ func ExampleLogger_Debug() {
} }
func ExampleLogger_Info() { func ExampleLogger_Info() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Info(). log.Info().
Str("foo", "bar"). Str("foo", "bar").
@ -129,7 +129,7 @@ func ExampleLogger_Info() {
} }
func ExampleLogger_Warn() { func ExampleLogger_Warn() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Warn(). log.Warn().
Str("foo", "bar"). Str("foo", "bar").
@ -139,7 +139,7 @@ func ExampleLogger_Warn() {
} }
func ExampleLogger_Error() { func ExampleLogger_Error() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Error(). log.Error().
Err(errors.New("some error")). Err(errors.New("some error")).
@ -149,16 +149,16 @@ func ExampleLogger_Error() {
} }
func ExampleLogger_WithLevel() { func ExampleLogger_WithLevel() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.WithLevel(zerolog.InfoLevel). log.WithLevel(zlog.InfoLevel).
Msg("hello world") Msg("hello world")
// Output: {"level":"info","message":"hello world"} // Output: {"level":"info","message":"hello world"}
} }
func ExampleLogger_Write() { func ExampleLogger_Write() {
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
@ -171,7 +171,7 @@ func ExampleLogger_Write() {
} }
func ExampleLogger_Log() { func ExampleLogger_Log() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
@ -182,11 +182,11 @@ func ExampleLogger_Log() {
} }
func ExampleEvent_Dict() { func ExampleEvent_Dict() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
Dict("dict", zerolog.Dict(). Dict("dict", zlog.Dict().
Str("bar", "baz"). Str("bar", "baz").
Int("n", 1), Int("n", 1),
). ).
@ -201,7 +201,7 @@ type User struct {
Created time.Time Created time.Time
} }
func (u User) MarshalZerologObject(e *zerolog.Event) { func (u User) MarshalZerologObject(e *zlog.Event) {
e.Str("name", u.Name). e.Str("name", u.Name).
Int("age", u.Age). Int("age", u.Age).
Time("created", u.Created) Time("created", u.Created)
@ -213,7 +213,7 @@ type Price struct {
unit string unit string
} }
func (p Price) MarshalZerologObject(e *zerolog.Event) { func (p Price) MarshalZerologObject(e *zlog.Event) {
denom := uint64(1) denom := uint64(1)
for i := 0; i < p.prec; i++ { for i := 0; i < p.prec; i++ {
denom *= 10 denom *= 10
@ -225,21 +225,21 @@ func (p Price) MarshalZerologObject(e *zerolog.Event) {
type Users []User type Users []User
func (uu Users) MarshalZerologArray(a *zerolog.Array) { func (uu Users) MarshalZerologArray(a *zlog.Array) {
for _, u := range uu { for _, u := range uu {
a.Object(u) a.Object(u)
} }
} }
func ExampleEvent_Array() { func ExampleEvent_Array() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
Array("array", zerolog.Arr(). Array("array", zlog.Arr().
Str("baz"). Str("baz").
Int(1). Int(1).
Dict(zerolog.Dict(). Dict(zlog.Dict().
Str("bar", "baz"). Str("bar", "baz").
Int("n", 1), Int("n", 1),
), ),
@ -250,9 +250,9 @@ func ExampleEvent_Array() {
} }
func ExampleEvent_Array_object() { func ExampleEvent_Array_object() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
// Users implements zerolog.LogArrayMarshaler // Users implements zlog.LogArrayMarshaler
u := Users{ u := Users{
User{"John", 35, time.Time{}}, User{"John", 35, time.Time{}},
User{"Bob", 55, time.Time{}}, User{"Bob", 55, time.Time{}},
@ -267,9 +267,9 @@ func ExampleEvent_Array_object() {
} }
func ExampleEvent_Object() { func ExampleEvent_Object() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
// User implements zerolog.LogObjectMarshaler // User implements zlog.LogObjectMarshaler
u := User{"John", 35, time.Time{}} u := User{"John", 35, time.Time{}}
log.Log(). log.Log().
@ -281,7 +281,7 @@ func ExampleEvent_Object() {
} }
func ExampleEvent_EmbedObject() { func ExampleEvent_EmbedObject() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
price := Price{val: 6449, prec: 2, unit: "$"} price := Price{val: 6449, prec: 2, unit: "$"}
@ -294,7 +294,7 @@ func ExampleEvent_EmbedObject() {
} }
func ExampleEvent_Interface() { func ExampleEvent_Interface() {
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
obj := struct { obj := struct {
Name string `json:"name"` Name string `json:"name"`
@ -313,7 +313,7 @@ func ExampleEvent_Interface() {
func ExampleEvent_Dur() { func ExampleEvent_Dur() {
d := 10 * time.Second d := 10 * time.Second
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
@ -329,7 +329,7 @@ func ExampleEvent_Durs() {
20 * time.Second, 20 * time.Second,
} }
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
@ -345,7 +345,7 @@ func ExampleEvent_Fields_map() {
"n": 1, "n": 1,
} }
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
@ -361,7 +361,7 @@ func ExampleEvent_Fields_slice() {
"n", 1, "n", 1,
} }
log := zerolog.New(os.Stdout) log := zlog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
@ -372,9 +372,9 @@ func ExampleEvent_Fields_slice() {
} }
func ExampleContext_Dict() { func ExampleContext_Dict() {
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Dict("dict", zerolog.Dict(). Dict("dict", zlog.Dict().
Str("bar", "baz"). Str("bar", "baz").
Int("n", 1), Int("n", 1),
).Logger() ).Logger()
@ -385,9 +385,9 @@ func ExampleContext_Dict() {
} }
func ExampleContext_Array() { func ExampleContext_Array() {
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Array("array", zerolog.Arr(). Array("array", zlog.Arr().
Str("baz"). Str("baz").
Int(1), Int(1),
).Logger() ).Logger()
@ -398,13 +398,13 @@ func ExampleContext_Array() {
} }
func ExampleContext_Array_object() { func ExampleContext_Array_object() {
// Users implements zerolog.LogArrayMarshaler // Users implements zlog.LogArrayMarshaler
u := Users{ u := Users{
User{"John", 35, time.Time{}}, User{"John", 35, time.Time{}},
User{"Bob", 55, time.Time{}}, User{"Bob", 55, time.Time{}},
} }
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Array("users", u). Array("users", u).
Logger() Logger()
@ -415,10 +415,10 @@ func ExampleContext_Array_object() {
} }
func ExampleContext_Object() { func ExampleContext_Object() {
// User implements zerolog.LogObjectMarshaler // User implements zlog.LogObjectMarshaler
u := User{"John", 35, time.Time{}} u := User{"John", 35, time.Time{}}
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Object("user", u). Object("user", u).
Logger() Logger()
@ -432,7 +432,7 @@ func ExampleContext_EmbedObject() {
price := Price{val: 6449, prec: 2, unit: "$"} price := Price{val: 6449, prec: 2, unit: "$"}
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
EmbedObject(price). EmbedObject(price).
Logger() Logger()
@ -449,7 +449,7 @@ func ExampleContext_Interface() {
Name: "john", Name: "john",
} }
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Interface("obj", obj). Interface("obj", obj).
Logger() Logger()
@ -462,7 +462,7 @@ func ExampleContext_Interface() {
func ExampleContext_Dur() { func ExampleContext_Dur() {
d := 10 * time.Second d := 10 * time.Second
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Dur("dur", d). Dur("dur", d).
Logger() Logger()
@ -478,7 +478,7 @@ func ExampleContext_Durs() {
20 * time.Second, 20 * time.Second,
} }
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Durs("durs", d). Durs("durs", d).
Logger() Logger()
@ -490,7 +490,7 @@ func ExampleContext_Durs() {
func ExampleContext_IPAddr() { func ExampleContext_IPAddr() {
hostIP := net.IP{192, 168, 0, 100} hostIP := net.IP{192, 168, 0, 100}
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
IPAddr("HostIP", hostIP). IPAddr("HostIP", hostIP).
Logger() Logger()
@ -501,7 +501,7 @@ func ExampleContext_IPAddr() {
func ExampleContext_IPPrefix() { func ExampleContext_IPPrefix() {
route := net.IPNet{IP: net.IP{192, 168, 0, 0}, Mask: net.CIDRMask(24, 32)} route := net.IPNet{IP: net.IP{192, 168, 0, 0}, Mask: net.CIDRMask(24, 32)}
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
IPPrefix("Route", route). IPPrefix("Route", route).
Logger() Logger()
@ -512,7 +512,7 @@ func ExampleContext_IPPrefix() {
func ExampleContext_MACAddr() { func ExampleContext_MACAddr() {
mac := net.HardwareAddr{0x00, 0x14, 0x22, 0x01, 0x23, 0x45} mac := net.HardwareAddr{0x00, 0x14, 0x22, 0x01, 0x23, 0x45}
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
MACAddr("hostMAC", mac). MACAddr("hostMAC", mac).
Logger() Logger()
@ -527,7 +527,7 @@ func ExampleContext_Fields_map() {
"n": 1, "n": 1,
} }
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Fields(fields). Fields(fields).
Logger() Logger()
@ -543,7 +543,7 @@ func ExampleContext_Fields_slice() {
"n", 1, "n", 1,
} }
log := zerolog.New(os.Stdout).With(). log := zlog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Fields(fields). Fields(fields).
Logger() Logger()

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"bytes" "bytes"

View File

@ -1,5 +1,5 @@
// +build !go1.12 // +build !go1.12
package zerolog package zlog
const contextCallerSkipFrameCount = 3 const contextCallerSkipFrameCount = 3

View File

@ -42,7 +42,7 @@ func frameField(f errors.Frame, s *state, c rune) string {
// MarshalStack implements pkg/errors stack trace marshaling. // MarshalStack implements pkg/errors stack trace marshaling.
// //
// zerolog.ErrorStackMarshaler = MarshalStack // zlog.ErrorStackMarshaler = MarshalStack
func MarshalStack(err error) interface{} { func MarshalStack(err error) interface{} {
type stackTracer interface { type stackTracer interface {
StackTrace() errors.StackTrace StackTrace() errors.StackTrace

View File

@ -8,14 +8,14 @@ import (
"testing" "testing"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/rs/zerolog" "git.tuxpa.in/a/zlog"
) )
func TestLogStack(t *testing.T) { func TestLogStack(t *testing.T) {
zerolog.ErrorStackMarshaler = MarshalStack zlog.ErrorStackMarshaler = MarshalStack
out := &bytes.Buffer{} out := &bytes.Buffer{}
log := zerolog.New(out) log := zlog.New(out)
err := errors.Wrap(errors.New("error message"), "from error") err := errors.Wrap(errors.New("error message"), "from error")
log.Log().Stack().Err(err).Msg("") log.Log().Stack().Err(err).Msg("")
@ -28,10 +28,10 @@ func TestLogStack(t *testing.T) {
} }
func TestLogStackFromContext(t *testing.T) { func TestLogStackFromContext(t *testing.T) {
zerolog.ErrorStackMarshaler = MarshalStack zlog.ErrorStackMarshaler = MarshalStack
out := &bytes.Buffer{} out := &bytes.Buffer{}
log := zerolog.New(out).With().Stack().Logger() // calling Stack() on log context instead of event log := zlog.New(out).With().Stack().Logger() // calling Stack() on log context instead of event
err := errors.Wrap(errors.New("error message"), "from error") err := errors.Wrap(errors.New("error message"), "from error")
log.Log().Err(err).Msg("") // not explicitly calling Stack() log.Log().Err(err).Msg("") // not explicitly calling Stack()
@ -44,9 +44,9 @@ func TestLogStackFromContext(t *testing.T) {
} }
func BenchmarkLogStack(b *testing.B) { func BenchmarkLogStack(b *testing.B) {
zerolog.ErrorStackMarshaler = MarshalStack zlog.ErrorStackMarshaler = MarshalStack
out := &bytes.Buffer{} out := &bytes.Buffer{}
log := zerolog.New(out) log := zlog.New(out)
err := errors.Wrap(errors.New("error message"), "from error") err := errors.Wrap(errors.New("error message"), "from error")
b.ReportAllocs() b.ReportAllocs()

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"math/rand" "math/rand"

View File

@ -1,6 +1,6 @@
// +build !binary_log // +build !binary_log
package zerolog package zlog
import ( import (
"testing" "testing"

View File

@ -1,7 +1,7 @@
// +build !windows // +build !windows
// +build !binary_log // +build !binary_log
package zerolog package zlog
import ( import (
"io" "io"
@ -28,7 +28,7 @@ type syslogWriter struct {
} }
// SyslogLevelWriter wraps a SyslogWriter and call the right syslog level // SyslogLevelWriter wraps a SyslogWriter and call the right syslog level
// method matching the zerolog level. // method matching the zlog level.
func SyslogLevelWriter(w SyslogWriter) LevelWriter { func SyslogLevelWriter(w SyslogWriter) LevelWriter {
return syslogWriter{w, ""} return syslogWriter{w, ""}
} }

View File

@ -1,7 +1,7 @@
// +build !binary_log // +build !binary_log
// +build !windows // +build !windows
package zerolog package zlog
import ( import (
"bytes" "bytes"

View File

@ -1,4 +1,4 @@
package zerolog package zlog
import ( import (
"bytes" "bytes"

View File

@ -1,7 +1,7 @@
//go:build !binary_log && !windows //go:build !binary_log && !windows
// +build !binary_log,!windows // +build !binary_log,!windows
package zerolog package zlog
import ( import (
"bytes" "bytes"