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
[![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.
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)
## 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
@ -33,26 +33,26 @@ Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog)
## Installation
```bash
go get -u github.com/rs/zerolog/log
go get -u git.tuxpa.in/a/zlog/log
```
## Getting Started
### 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
package main
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
// UNIX Time is faster and smaller than most timestamps
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Print("hello world")
}
@ -64,18 +64,18 @@ func main() {
### 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
package main
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Debug().
Str("Scale", "833 cents").
@ -101,12 +101,12 @@ func main() {
package main
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Info().Msg("hello world")
}
@ -114,19 +114,19 @@ func main() {
// 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)
* fatal (`zerolog.FatalLevel`, 4)
* error (`zerolog.ErrorLevel`, 3)
* warn (`zerolog.WarnLevel`, 2)
* info (`zerolog.InfoLevel`, 1)
* debug (`zerolog.DebugLevel`, 0)
* trace (`zerolog.TraceLevel`, -1)
* panic (`zlog.PanicLevel`, 5)
* fatal (`zlog.FatalLevel`, 4)
* error (`zlog.ErrorLevel`, 3)
* warn (`zlog.WarnLevel`, 2)
* info (`zlog.InfoLevel`, 1)
* debug (`zlog.DebugLevel`, 0)
* 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
@ -138,20 +138,20 @@ package main
import (
"flag"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.TimeFieldFormat = zlog.TimeFormatUnix
debug := flag.Bool("debug", false, "sets log level to debug")
flag.Parse()
// Default level for this example is info, unless debug flag is present
zerolog.SetGlobalLevel(zerolog.InfoLevel)
zlog.SetGlobalLevel(zlog.InfoLevel)
if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
zlog.SetGlobalLevel(zlog.DebugLevel)
}
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
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Log().
Str("foo", "bar").
@ -214,12 +214,12 @@ package main
import (
"errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.TimeFieldFormat = zlog.TimeFormatUnix
err := errors.New("seems we have an error here")
log.Error().Err(err).Msg("")
@ -228,7 +228,7 @@ func main() {
// 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
@ -239,15 +239,15 @@ package main
import (
"github.com/pkg/errors"
"github.com/rs/zerolog/pkgerrors"
"git.tuxpa.in/a/zlog/pkgerrors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
zlog.TimeFieldFormat = zlog.TimeFormatUnix
zlog.ErrorStackMarshaler = pkgerrors.MarshalStack
err := outer()
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}
```
> 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
@ -286,15 +286,15 @@ package main
import (
"errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
err := errors.New("A repo man spends his life getting into tense situations")
service := "myservice"
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.TimeFieldFormat = zlog.TimeFormatUnix
log.Fatal().
Err(err).
@ -312,7 +312,7 @@ func main() {
### Create logger instance to manage different outputs
```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")
@ -332,10 +332,10 @@ sublogger.Info().Msg("hello world")
### Pretty logging
To log a human-friendly, colorized output, use `zerolog.ConsoleWriter`:
To log a human-friendly, colorized output, use `zlog.ConsoleWriter`:
```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")
@ -345,7 +345,7 @@ log.Info().Str("foo", "bar").Msg("Hello world")
To customize the configuration and formatting:
```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 {
return strings.ToUpper(fmt.Sprintf("| %-6s|", i))
}
@ -359,7 +359,7 @@ output.FormatFieldValue = func(i interface{}) string {
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")
@ -371,7 +371,7 @@ log.Info().Str("foo", "bar").Msg("Hello World")
```go
log.Info().
Str("foo", "bar").
Dict("dict", zerolog.Dict().
Dict("dict", zlog.Dict().
Str("bar", "baz").
Int("n", 1),
).Msg("hello world")
@ -382,9 +382,9 @@ log.Info().
### Customize automatic field names
```go
zerolog.TimestampFieldName = "t"
zerolog.LevelFieldName = "l"
zerolog.MessageFieldName = "m"
zlog.TimestampFieldName = "t"
zlog.LevelFieldName = "l"
zlog.MessageFieldName = "m"
log.Info().Msg("hello world")
@ -411,7 +411,7 @@ log.Info().Msg("hello world")
Equivalent of `Lshortfile`:
```go
zerolog.CallerMarshalFunc = func(file string, line int) string {
zlog.CallerMarshalFunc = func(file string, line int) string {
short := file
for i := len(file) - 1; i > 0; 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) {
fmt.Printf("Logger Dropped %d messages", missed)
})
log := zerolog.New(wr)
log := zlog.New(wr)
log.Print("test")
```
@ -445,7 +445,7 @@ You will need to install `code.cloudfoundry.org/go-diodes` to use this feature.
### Log Sampling
```go
sampled := log.Sample(&zerolog.BasicSampler{N: 10})
sampled := log.Sample(&zlog.BasicSampler{N: 10})
sampled.Info().Msg("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.
// Over 5 debug message, 1 every 100 debug messages are logged.
// Other levels are not sampled.
sampled := log.Sample(zerolog.LevelSampler{
DebugSampler: &zerolog.BurstSampler{
sampled := log.Sample(zlog.LevelSampler{
DebugSampler: &zlog.BurstSampler{
Burst: 5,
Period: 1*time.Second,
NextSampler: &zerolog.BasicSampler{N: 100},
NextSampler: &zlog.BasicSampler{N: 100},
},
})
sampled.Debug().Msg("hello world")
@ -474,8 +474,8 @@ sampled.Debug().Msg("hello world")
```go
type SeverityHook struct{}
func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
if level != zerolog.NoLevel {
func (h SeverityHook) Run(e *zlog.Event, level zlog.Level, msg string) {
if level != zlog.NoLevel {
e.Str("severity", level.String())
}
}
@ -499,7 +499,7 @@ log.Ctx(ctx).Info().Msg("hello world")
### Set as standard logger output
```go
log := zerolog.New(os.Stdout).With().
log := zlog.New(os.Stdout).With().
Str("foo", "bar").
Logger()
@ -513,12 +513,12 @@ stdlog.Print("hello world")
### 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.
```go
log := zerolog.New(os.Stdout).With().
log := zlog.New(os.Stdout).With().
Timestamp().
Str("role", "my-service").
Str("host", host).
@ -565,15 +565,15 @@ if err := http.ListenAndServe(":8080", nil); err != nil {
```
## 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.
```go
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!")
}
@ -588,16 +588,16 @@ func main() {
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).
* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zerolog.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.
* `zerolog.TimestampFieldName`: Can be set to customize `Timestamp` field name.
* `zerolog.LevelFieldName`: Can be set to customize level field name.
* `zerolog.MessageFieldName`: Can be set to customize message field name.
* `zerolog.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.
* `zerolog.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`).
* `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.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zlog.Disabled` to disable logging altogether (quiet mode).
* `zlog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events.
* `zlog.TimestampFieldName`: Can be set to customize `Timestamp` field name.
* `zlog.LevelFieldName`: Can be set to customize level field name.
* `zlog.MessageFieldName`: Can be set to customize message field name.
* `zlog.ErrorFieldName`: Can be set to customize `Err` field name.
* `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.
* `zlog.DurationFieldUnit`: Can be set to customize the unit for time.Duration type fields added by `Dur` (default: `time.Millisecond`).
* `zlog.DurationFieldInteger`: If set to `true`, `Dur` fields are formatted as integers instead of floats (default: `false`).
* `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
@ -611,10 +611,10 @@ Some settings can be changed and will be applied to all loggers:
### 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.
* `Timestamp`: Inserts a timestamp field with `zerolog.TimestampFieldName` field name, formatted using `zerolog.TimeFieldFormat`.
* `Time`: Adds a field with time formatted with `zerolog.TimeFieldFormat`.
* `Timestamp`: Inserts a timestamp field with `zlog.TimestampFieldName` field name, formatted using `zlog.TimeFieldFormat`.
* `Time`: Adds a field with time formatted with `zlog.TimeFieldFormat`.
* `Dur`: Adds a field with `time.Duration`.
* `Dict`: Adds a sub-key/value as a field of the event.
* `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
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
go build -tags binary_log .
```
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
* [grpc-zerolog](https://github.com/cheapRoc/grpc-zerolog): Implementation of `grpclog.LoggerV2` interface using `zerolog`
* [overlog](https://github.com/Trendyol/overlog): Implementation of `Mapped Diagnostic Context` interface using `zerolog`
* [zerologr](https://github.com/go-logr/zerologr): Implementation of `logr.LogSink` 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 `zlog`
* [zlogr](https://github.com/go-logr/zlogr): Implementation of `logr.LogSink` interface using `zlog`
## 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
```
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)
* [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 |
| :--- | :---: | :---: | :---: |
| 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 (sugared) | 1363 ns/op | 1610 B/op | 20 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 |
| :--- | :---: | :---: | :---: |
| 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 (sugared) | 337 ns/op | 80 B/op | 2 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 |
| :--- | :---: | :---: | :---: |
| 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 |
| standard library | 453 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
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
logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
logger := zlog.New(os.Stderr).With().Timestamp().Logger()
logger.Info().
Timestamp().
Msg("dup")

View File

@ -1,4 +1,4 @@
package zerolog
package zlog
import (
"net"
@ -193,7 +193,7 @@ func (a *Array) Float64(f float64) *Array {
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 {
a.buf = enc.AppendTime(enc.AppendArrayDelim(a.buf), t, TimeFieldFormat)
return a

View File

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

View File

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

View File

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

View File

@ -4,13 +4,13 @@ This is a basic linter that checks for missing log event finishers. Finds errors
## 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
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
@ -33,5 +33,5 @@ The command accepts only one argument - the package to be inspected - and 4 opti
## 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

View File

@ -29,8 +29,8 @@ func init() {
flag.Var(&allowedFinishers, "finisher", "allowed finisher for the event chain")
flag.Parse()
// add zerolog to recursively ignored packages
recursivelyIgnoredPkgs = append(recursivelyIgnoredPkgs, "github.com/rs/zerolog")
// add zlog to recursively ignored packages
recursivelyIgnoredPkgs = append(recursivelyIgnoredPkgs, "git.tuxpa.in/a/zlog")
args := flag.Args()
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "you must provide exactly one package path")
@ -49,14 +49,14 @@ func main() {
os.Exit(1)
}
// get the github.com/rs/zerolog.Event type
// get the git.tuxpa.in/a/zlog.Event type
event := getEvent(p)
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)
}
// 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)
// print the violations (if any)
@ -80,7 +80,7 @@ func main() {
func getEvent(p *loader.Program) types.Type {
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 {
if d != nil && d.Name() == "Event" {
return d.Type()

View File

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

View File

@ -1,4 +1,4 @@
package zerolog_test
package zlog_test
import (
"bytes"
@ -9,39 +9,39 @@ import (
"testing"
"time"
"github.com/rs/zerolog"
"git.tuxpa.in/a/zlog"
)
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")
// Output: <nil> INF Hello World foo=bar
}
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.FormatFieldName = func(i interface{}) string { return 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")
// Output: <nil> INFO | Hello World foo:BAR
}
func ExampleNewConsoleWriter() {
out := zerolog.NewConsoleWriter()
out := zlog.NewConsoleWriter()
out.NoColor = true // For testing purposes only
log := zerolog.New(out)
log := zlog.New(out)
log.Debug().Str("foo", "bar").Msg("Hello World")
// Output: <nil> DBG Hello World foo=bar
}
func ExampleNewConsoleWriter_customFormatters() {
out := zerolog.NewConsoleWriter(
func(w *zerolog.ConsoleWriter) {
out := zlog.NewConsoleWriter(
func(w *zlog.ConsoleWriter) {
// Customize time format
w.TimeFormat = time.RFC822
// Customize level formatting
@ -50,7 +50,7 @@ func ExampleNewConsoleWriter_customFormatters() {
)
out.NoColor = true // For testing purposes only
log := zerolog.New(out)
log := zlog.New(out)
log.Info().Str("foo", "bar").Msg("Hello World")
// Output: <nil> [INFO ] Hello World foo=bar
@ -59,7 +59,7 @@ func ExampleNewConsoleWriter_customFormatters() {
func TestConsoleLogger(t *testing.T) {
t.Run("Numbers", func(t *testing.T) {
buf := &bytes.Buffer{}
log := zerolog.New(zerolog.ConsoleWriter{Out: buf, NoColor: true})
log := zlog.New(zlog.ConsoleWriter{Out: buf, NoColor: true})
log.Info().
Float64("float", 1.23).
Uint64("small", 123).
@ -74,7 +74,7 @@ func TestConsoleLogger(t *testing.T) {
func TestConsoleWriter(t *testing.T) {
t.Run("Default field formatter", func(t *testing.T) {
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"}`))
if err != nil {
@ -90,7 +90,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write colorized", func(t *testing.T) {
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"}`))
if err != nil {
@ -106,7 +106,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write fields", func(t *testing.T) {
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)
_, 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) {
of := zerolog.TimeFieldFormat
of := zlog.TimeFieldFormat
defer func() {
zerolog.TimeFieldFormat = of
zlog.TimeFieldFormat = of
}()
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.TimeFieldFormat = zlog.TimeFormatUnix
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"}`))
if err != nil {
@ -144,14 +144,14 @@ func TestConsoleWriter(t *testing.T) {
})
t.Run("Unix timestamp ms input format", func(t *testing.T) {
of := zerolog.TimeFieldFormat
of := zlog.TimeFieldFormat
defer func() {
zerolog.TimeFieldFormat = of
zlog.TimeFieldFormat = of
}()
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs
zlog.TimeFieldFormat = zlog.TimeFormatUnixMs
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"}`))
if err != nil {
@ -166,14 +166,14 @@ func TestConsoleWriter(t *testing.T) {
})
t.Run("Unix timestamp us input format", func(t *testing.T) {
of := zerolog.TimeFieldFormat
of := zlog.TimeFieldFormat
defer func() {
zerolog.TimeFieldFormat = of
zlog.TimeFieldFormat = of
}()
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMicro
zlog.TimeFieldFormat = zlog.TimeFormatUnixMicro
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"}`))
if err != nil {
@ -189,7 +189,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("No message field", func(t *testing.T) {
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"}`))
if err != nil {
@ -205,7 +205,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("No level field", func(t *testing.T) {
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"}`))
if err != nil {
@ -221,7 +221,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write colorized fields", func(t *testing.T) {
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"}`))
if err != nil {
@ -237,7 +237,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write error field", func(t *testing.T) {
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)
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) {
buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true}
w := zlog.ConsoleWriter{Out: buf, NoColor: true}
cwd, err := os.Getwd()
if err != nil {
@ -282,7 +282,7 @@ func TestConsoleWriter(t *testing.T) {
t.Run("Write JSON field", func(t *testing.T) {
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}`
// t.Log(evt)
@ -303,7 +303,7 @@ func TestConsoleWriter(t *testing.T) {
func TestConsoleWriterConfiguration(t *testing.T) {
t.Run("Sets TimeFormat", func(t *testing.T) {
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)
evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}`
@ -322,7 +322,7 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Run("Sets PartsOrder", func(t *testing.T) {
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"}`
_, err := w.Write([]byte(evt))
@ -339,7 +339,7 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Run("Sets PartsExclude", func(t *testing.T) {
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)
evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}`
@ -357,7 +357,7 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Run("Sets FieldsExclude", func(t *testing.T) {
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"}`
_, 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"}`)
w := zerolog.ConsoleWriter{Out: ioutil.Discard, NoColor: false}
w := zlog.ConsoleWriter{Out: ioutil.Discard, NoColor: false}
for i := 0; i < b.N; i++ {
w.Write(msg)

View File

@ -1,4 +1,4 @@
package zerolog
package zlog
import (
"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.
// 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.
func (c Context) Array(key string, arr LogArrayMarshaler) Context {
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{}
// 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.
func (c Context) Timestamp() Context {
@ -338,13 +338,13 @@ func (c Context) Timestamp() Context {
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 {
c.l.context = enc.AppendTime(enc.AppendKey(c.l.context, key), t, TimeFieldFormat)
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 {
c.l.context = enc.AppendTimes(enc.AppendKey(c.l.context, key), t, TimeFieldFormat)
return c
@ -394,13 +394,13 @@ const useGlobalSkipFrameCount = math.MinInt32
// ch is the default caller hook using the global CallerSkipFrameCount.
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 {
c.l = c.l.Hook(ch)
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.
// If set to -1 the global CallerSkipFrameCount will be used.
func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context {

4
ctx.go
View File

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

View File

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

View File

@ -8,7 +8,7 @@ import (
"sync"
"time"
"github.com/rs/zerolog/diode/internal/diodes"
"git.tuxpa.in/a/zlog/diode/internal/diodes"
)
var bufPool = &sync.Pool{
@ -42,7 +42,7 @@ type Writer struct {
// wr := diode.NewWriter(w, 1000, 0, func(missed int) {
// 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
// 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) {
// 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.
p = append(bufPool.Get().([]byte), p...)
dw.d.Set(diodes.GenericDataType(&p))

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package zerolog
package zlog
import (
"fmt"
@ -150,7 +150,7 @@ func (e *Event) msg(msg string) {
if ErrorHandler != nil {
ErrorHandler(err)
} 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.
// Use zerolog.Dict() to create the dictionary.
// Use zlog.Dict() to create the dictionary.
func (e *Event) Dict(key string, dict *Event) *Event {
if e == nil {
return e
@ -186,7 +186,7 @@ func Dict() *Event {
}
// 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.
func (e *Event) Array(key string, arr LogArrayMarshaler) *Event {
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.
// 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
// zerolog.ErrorStackFieldName.
// zlog.ErrorStackFieldName.
func (e *Event) Err(err error) *Event {
if e == nil {
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.
// 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
// already.
@ -652,7 +652,7 @@ func (e *Event) Timestamp() *Event {
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 {
if e == nil {
return e
@ -661,7 +661,7 @@ func (e *Event) Time(key string, t time.Time) *Event {
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 {
if e == nil {
return e
@ -670,8 +670,8 @@ func (e *Event) Times(key string, t []time.Time) *Event {
return e
}
// Dur adds the field key with duration d stored as zerolog.DurationFieldUnit.
// If zerolog.DurationFieldInteger is true, durations are rendered as integer
// Dur adds the field key with duration d stored as zlog.DurationFieldUnit.
// If zlog.DurationFieldInteger is true, durations are rendered as integer
// instead of float.
func (e *Event) Dur(key string, d time.Duration) *Event {
if e == nil {
@ -681,8 +681,8 @@ func (e *Event) Dur(key string, d time.Duration) *Event {
return e
}
// Durs adds the field key with duration d stored as zerolog.DurationFieldUnit.
// If zerolog.DurationFieldInteger is true, durations are rendered as integer
// Durs adds the field key with duration d stored as zlog.DurationFieldUnit.
// If zlog.DurationFieldInteger is true, durations are rendered as integer
// instead of float.
func (e *Event) Durs(key string, d []time.Duration) *Event {
if e == nil {
@ -729,7 +729,7 @@ func (e *Event) CallerSkipFrame(skip int) *Event {
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
// Skip If not passed, use the global variable CallerSkipFrameCount
func (e *Event) Caller(skip ...int) *Event {

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package zerolog
package zlog
import (
"encoding/json"
@ -96,7 +96,7 @@ var (
// set to true.
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
// be thread safe and non-blocking.
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

View File

@ -1,6 +1,6 @@
// +build go1.12
package zerolog
package zlog
// Since go 1.12, some auto generated init functions are hidden from
// 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
import (
@ -7,19 +7,19 @@ import (
"time"
"github.com/rs/xid"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog/internal/mutil"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/hlog/internal/mutil"
"git.tuxpa.in/a/zlog/log"
)
// FromRequest gets the logger in the request's 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())
}
// 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 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 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 {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, r.URL.String())
})
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 {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, r.Method)
})
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 {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, r.Method+" "+r.URL.String())
})
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 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RemoteAddr != "" {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context {
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 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ua := r.Header.Get("User-Agent"); ua != "" {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context {
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 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ref := r.Header.Get("Referer"); ref != "" {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, ref)
})
}
@ -162,8 +162,8 @@ func RequestIDHandler(fieldKey, headerName string) func(next http.Handler) http.
r = r.WithContext(ctx)
}
if fieldKey != "" {
log := zerolog.Ctx(ctx)
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
log := zlog.Ctx(ctx)
log.UpdateContext(func(c zlog.Context) zlog.Context {
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 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if val := r.Header.Get(header); val != "" {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
log := zlog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, val)
})
}

View File

@ -9,8 +9,8 @@ import (
"net/http/httptest"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/hlog"
)
// fake alice to avoid dep
@ -31,13 +31,13 @@ func (a alice) Then(h http.Handler) http.Handler {
}
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)
}
}
func Example_handler() {
log := zerolog.New(os.Stdout).With().
log := zlog.New(os.Stdout).With().
Timestamp().
Str("role", "my-service").
Str("host", "local-hostname").

View File

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

View File

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

View File

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

View File

@ -8,7 +8,7 @@ import (
"os"
"time"
"github.com/rs/zerolog"
"git.tuxpa.in/a/zlog"
)
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) }
log := zerolog.New(f).With().
zlog.TimestampFunc = func() time.Time { return time.Now().Round(time.Second) }
log := zlog.New(f).With().
Timestamp().
Logger()
for i := 0; i < count; i++ {

View File

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

View File

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

View File

@ -7,12 +7,12 @@ import (
"io"
"testing"
"github.com/rs/zerolog"
"github.com/rs/zerolog/journald"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/journald"
)
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")
// Output:
}
@ -71,14 +71,14 @@ func TestMultiWrite(t *testing.T) {
w3 = journald.NewJournalDWriter()
)
zerolog.ErrorHandler = func(err error) {
zlog.ErrorHandler = func(err error) {
if err == io.ErrShortWrite {
t.Errorf("Unexpected ShortWriteError")
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++ {
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:
//
// import "github.com/rs/zerolog/log"
// import "git.tuxpa.in/a/zlog/log"
//
// log.Info().Msg("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:
//
@ -16,7 +16,7 @@
//
// 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().
// Str("foo", "bar").
// Msg("hello world")
@ -30,7 +30,7 @@
//
// Level logging
//
// zerolog.SetGlobalLevel(zerolog.InfoLevel)
// zlog.SetGlobalLevel(zlog.InfoLevel)
//
// log.Debug().Msg("filtered out message")
// log.Info().Msg("routed message")
@ -62,7 +62,7 @@
//
// 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")
//
// Log with contextual hooks:
@ -70,15 +70,15 @@
// // Create the hook:
// type SeverityHook struct{}
//
// func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
// if level != zerolog.NoLevel {
// func (h SeverityHook) Run(e *zlog.Event, level zlog.Level, msg string) {
// if level != zlog.NoLevel {
// e.Str("severity", level.String())
// }
// }
//
// // And use it:
// var h SeverityHook
// log := zerolog.New(os.Stdout).Hook(h)
// log := zlog.New(os.Stdout).Hook(h)
// log.Warn().Msg("")
// // Output: {"level":"warn","severity":"warn"}
//
@ -88,7 +88,7 @@
// There is no fields deduplication out-of-the-box.
// 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().
// Timestamp().
// Msg("dup")
@ -96,7 +96,7 @@
//
// In this case, many consumers will take the last value,
// but this is not guaranteed; check yours if in doubt.
package zerolog
package zlog
import (
"fmt"
@ -156,7 +156,7 @@ func (l Level) String() string {
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.
func ParseLevel(levelStr string) (Level, error) {
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
import (
@ -6,35 +6,40 @@ import (
"fmt"
"io"
"os"
"time"
"github.com/rs/zerolog"
"git.tuxpa.in/a/zlog"
)
// 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.
func Output(w io.Writer) zerolog.Logger {
func Output(w io.Writer) zlog.Logger {
return Logger.Output(w)
}
// With creates a child logger with the field added to its context.
func With() zerolog.Context {
func With() zlog.Context {
return Logger.With()
}
// 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)
}
// 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)
}
// 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)
}
@ -42,73 +47,99 @@ func Hook(h zerolog.Hook) zerolog.Logger {
// with info level if err is nil.
//
// You must call Msg on the returned event in order to send the event.
func Err(err error) *zerolog.Event {
func Err(err error) *zlog.Event {
return Logger.Err(err)
}
// Trace starts a new message with trace level.
//
// You must call Msg on the returned event in order to send the event.
func Trace() *zerolog.Event {
func Trace() *zlog.Event {
return Logger.Trace()
}
// Debug starts a new message with debug level.
//
// 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()
}
// Info starts a new message with info level.
//
// 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()
}
// Warn starts a new message with warn level.
//
// 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()
}
// Error starts a new message with error level.
//
// 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()
}
// 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
// is called by the Msg method.
//
// 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()
}
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
// to the panic function.
//
// 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()
}
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.
//
// 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)
}
// Log starts a new message with no level. Setting zerolog.GlobalLevel to
// zerolog.Disabled will still disable events produced by this method.
// Log starts a new message with no level. Setting zlog.GlobalLevel to
// zlog.Disabled will still disable events produced by this method.
//
// 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()
}
@ -124,8 +155,12 @@ func Printf(format string, v ...interface{}) {
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
// is associated, a disabled logger is returned.
func Ctx(ctx context.Context) *zerolog.Logger {
return zerolog.Ctx(ctx)
func Ctx(ctx context.Context) *zlog.Logger {
return zlog.Ctx(ctx)
}

View File

@ -1,3 +1,4 @@
//go:build !binary_log
// +build !binary_log
package log_test
@ -8,8 +9,8 @@ import (
"os"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
// setup would normally be an init() function, however, there seems
@ -17,16 +18,16 @@ import (
// global Logger from an init()
func setup() {
// 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
zerolog.TimeFieldFormat = ""
zlog.TimeFieldFormat = ""
// 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
zerolog.TimestampFunc = func() time.Time {
zlog.TimestampFunc = func() time.Time {
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
@ -130,9 +131,9 @@ func Example() {
flag.Parse()
// Default level for this example is info, unless debug flag is present
zerolog.SetGlobalLevel(zerolog.InfoLevel)
zlog.SetGlobalLevel(zlog.InfoLevel)
if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
zlog.SetGlobalLevel(zlog.DebugLevel)
}
log.Debug().Msg("This message appears only when log level set to Debug")

View File

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

View File

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

View File

@ -1,5 +1,5 @@
// +build !go1.12
package zerolog
package zlog
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.
//
// zerolog.ErrorStackMarshaler = MarshalStack
// zlog.ErrorStackMarshaler = MarshalStack
func MarshalStack(err error) interface{} {
type stackTracer interface {
StackTrace() errors.StackTrace

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
// +build !windows
// +build !binary_log
package zerolog
package zlog
import (
"io"
@ -28,7 +28,7 @@ type syslogWriter struct {
}
// 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 {
return syslogWriter{w, ""}
}

View File

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

View File

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

View File

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