Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot] 5e6ec5804d
Bump actions/checkout from 2 to 3
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-07 06:09:31 +00:00
60 changed files with 532 additions and 1067 deletions

View File

@ -4,17 +4,17 @@ jobs:
test: test:
strategy: strategy:
matrix: matrix:
go-version: [1.18.x, 1.19.x] go-version: [1.15.x, 1.16.x]
os: [ubuntu-latest, macos-latest] os: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Install Go - name: Install Go
uses: actions/setup-go@v4 uses: actions/setup-go@v2
with: with:
go-version: ${{ matrix.go-version }} go-version: ${{ matrix.go-version }}
- name: Checkout code - name: Checkout code
uses: actions/checkout@v3 uses: actions/checkout@v3
- uses: actions/cache@v3 - uses: actions/cache@v2
with: with:
path: ~/go/pkg/mod path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}

2
CNAME
View File

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

249
README.md
View File

@ -1,26 +1,20 @@
###zlog
opinionated defaults on zerolog
# Zero Allocation JSON Logger # Zero Allocation JSON Logger
[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/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/tuxpa.in/a/zlog)](http://gocover.io/tuxpa.in/a/zlog) [![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)
The zlog package provides a fast and simple logger dedicated to JSON output. The zerolog 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 zlog 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 zerolog 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, zlog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) [`zlog.ConsoleWriter`](#pretty-logging). 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).
![Pretty Logging Image](pretty.png) ![Pretty Logging Image](pretty.png)
## Who uses zlog ## Who uses zerolog
Find out [who uses zlog](https://tuxpa.in/a/zlog/wiki/Who-uses-zlog) and add your company / project to the list. Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog) and add your company / project to the list.
## Features ## Features
@ -30,7 +24,7 @@ Find out [who uses zlog](https://tuxpa.in/a/zlog/wiki/Who-uses-zlog) and add you
* [Sampling](#log-sampling) * [Sampling](#log-sampling)
* [Hooks](#hooks) * [Hooks](#hooks)
* [Contextual fields](#contextual-logging) * [Contextual fields](#contextual-logging)
* [`context.Context` integration](#contextcontext-integration) * `context.Context` integration
* [Integration with `net/http`](#integration-with-nethttp) * [Integration with `net/http`](#integration-with-nethttp)
* [JSON and CBOR encoding formats](#binary-encoding) * [JSON and CBOR encoding formats](#binary-encoding)
* [Pretty logging for development](#pretty-logging) * [Pretty logging for development](#pretty-logging)
@ -39,26 +33,26 @@ Find out [who uses zlog](https://tuxpa.in/a/zlog/wiki/Who-uses-zlog) and add you
## Installation ## Installation
```bash ```bash
go get -u tuxpa.in/a/zlog/log go get -u github.com/rs/zerolog/log
``` ```
## Getting Started ## Getting Started
### Simple Logging Example ### Simple Logging Example
For simple logging, import the global logger package **tuxpa.in/a/zlog/log** For simple logging, import the global logger package **github.com/rs/zerolog/log**
```go ```go
package main package main
import ( import (
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/log"
) )
func main() { func main() {
// UNIX Time is faster and smaller than most timestamps // UNIX Time is faster and smaller than most timestamps
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Print("hello world") log.Print("hello world")
} }
@ -70,18 +64,18 @@ func main() {
### Contextual Logging ### Contextual Logging
**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: **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:
```go ```go
package main package main
import ( import (
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/log"
) )
func main() { func main() {
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Debug(). log.Debug().
Str("Scale", "833 cents"). Str("Scale", "833 cents").
@ -107,12 +101,12 @@ func main() {
package main package main
import ( import (
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/log"
) )
func main() { func main() {
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Info().Msg("hello world") log.Info().Msg("hello world")
} }
@ -120,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 **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. > 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.
**zlog** allows for logging at the following levels (from highest to lowest): **zerolog** allows for logging at the following levels (from highest to lowest):
* panic (`zlog.PanicLevel`, 5) * panic (`zerolog.PanicLevel`, 5)
* fatal (`zlog.FatalLevel`, 4) * fatal (`zerolog.FatalLevel`, 4)
* error (`zlog.ErrorLevel`, 3) * error (`zerolog.ErrorLevel`, 3)
* warn (`zlog.WarnLevel`, 2) * warn (`zerolog.WarnLevel`, 2)
* info (`zlog.InfoLevel`, 1) * info (`zerolog.InfoLevel`, 1)
* debug (`zlog.DebugLevel`, 0) * debug (`zerolog.DebugLevel`, 0)
* trace (`zlog.TraceLevel`, -1) * trace (`zerolog.TraceLevel`, -1)
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. 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.
#### Setting Global Log Level #### Setting Global Log Level
@ -144,20 +138,20 @@ package main
import ( import (
"flag" "flag"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/log"
) )
func main() { func main() {
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.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
zlog.SetGlobalLevel(zlog.InfoLevel) zerolog.SetGlobalLevel(zerolog.InfoLevel)
if *debug { if *debug {
zlog.SetGlobalLevel(zlog.DebugLevel) zerolog.SetGlobalLevel(zerolog.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")
@ -195,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 (
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/log"
) )
func main() { func main() {
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
@ -220,12 +214,12 @@ package main
import ( import (
"errors" "errors"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/log"
) )
func main() { func main() {
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.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("")
@ -234,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 `zlog.ErrorFieldName` to meet your needs. > The default field name for errors is `error`, you can change this by setting `zerolog.ErrorFieldName` to meet your needs.
#### Error Logging with Stacktrace #### Error Logging with Stacktrace
@ -245,15 +239,15 @@ package main
import ( import (
"github.com/pkg/errors" "github.com/pkg/errors"
"tuxpa.in/a/zlog/pkgerrors" "github.com/rs/zerolog/pkgerrors"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/log"
) )
func main() { func main() {
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zlog.ErrorStackMarshaler = pkgerrors.MarshalStack zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
err := outer() err := outer()
log.Error().Stack().Err(err).Msg("") log.Error().Stack().Err(err).Msg("")
@ -282,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}
``` ```
> zlog.ErrorStackMarshaler must be set in order for the stack to output anything. > zerolog.ErrorStackMarshaler must be set in order for the stack to output anything.
#### Logging Fatal Messages #### Logging Fatal Messages
@ -292,15 +286,15 @@ package main
import ( import (
"errors" "errors"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/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"
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Fatal(). log.Fatal().
Err(err). Err(err).
@ -318,7 +312,7 @@ func main() {
### Create logger instance to manage different outputs ### Create logger instance to manage different outputs
```go ```go
logger := zlog.New(os.Stderr).With().Timestamp().Logger() logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
logger.Info().Str("foo", "bar").Msg("hello world") logger.Info().Str("foo", "bar").Msg("hello world")
@ -338,10 +332,10 @@ sublogger.Info().Msg("hello world")
### Pretty logging ### Pretty logging
To log a human-friendly, colorized output, use `zlog.ConsoleWriter`: To log a human-friendly, colorized output, use `zerolog.ConsoleWriter`:
```go ```go
log.Logger = log.Output(zlog.ConsoleWriter{Out: os.Stderr}) log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
log.Info().Str("foo", "bar").Msg("Hello world") log.Info().Str("foo", "bar").Msg("Hello world")
@ -351,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 := zlog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339} output := zerolog.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))
} }
@ -365,7 +359,7 @@ output.FormatFieldValue = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("%s", i)) return strings.ToUpper(fmt.Sprintf("%s", i))
} }
log := zlog.New(output).With().Timestamp().Logger() log := zerolog.New(output).With().Timestamp().Logger()
log.Info().Str("foo", "bar").Msg("Hello World") log.Info().Str("foo", "bar").Msg("Hello World")
@ -377,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", zlog.Dict(). Dict("dict", zerolog.Dict().
Str("bar", "baz"). Str("bar", "baz").
Int("n", 1), Int("n", 1),
).Msg("hello world") ).Msg("hello world")
@ -388,9 +382,9 @@ log.Info().
### Customize automatic field names ### Customize automatic field names
```go ```go
zlog.TimestampFieldName = "t" zerolog.TimestampFieldName = "t"
zlog.LevelFieldName = "l" zerolog.LevelFieldName = "l"
zlog.MessageFieldName = "m" zerolog.MessageFieldName = "m"
log.Info().Msg("hello world") log.Info().Msg("hello world")
@ -405,8 +399,6 @@ log.Logger = log.With().Str("foo", "bar").Logger()
### Add file and line number to log ### Add file and line number to log
Equivalent of `Llongfile`:
```go ```go
log.Logger = log.With().Caller().Logger() log.Logger = log.With().Caller().Logger()
log.Info().Msg("hello world") log.Info().Msg("hello world")
@ -414,25 +406,6 @@ log.Info().Msg("hello world")
// Output: {"level": "info", "message": "hello world", "caller": "/go/src/your_project/some_file:21"} // Output: {"level": "info", "message": "hello world", "caller": "/go/src/your_project/some_file:21"}
``` ```
Equivalent of `Lshortfile`:
```go
zlog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
}
log.Logger = log.With().Caller().Logger()
log.Info().Msg("hello world")
// Output: {"level": "info", "message": "hello world", "caller": "some_file:21"}
```
### Thread-safe, lock-free, non-blocking writer ### Thread-safe, lock-free, non-blocking writer
@ -442,7 +415,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 := zlog.New(wr) log := zerolog.New(wr)
log.Print("test") log.Print("test")
``` ```
@ -451,7 +424,7 @@ You will need to install `code.cloudfoundry.org/go-diodes` to use this feature.
### Log Sampling ### Log Sampling
```go ```go
sampled := log.Sample(&zlog.BasicSampler{N: 10}) sampled := log.Sample(&zerolog.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"}
@ -463,11 +436,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(zlog.LevelSampler{ sampled := log.Sample(zerolog.LevelSampler{
DebugSampler: &zlog.BurstSampler{ DebugSampler: &zerolog.BurstSampler{
Burst: 5, Burst: 5,
Period: 1*time.Second, Period: 1*time.Second,
NextSampler: &zlog.BasicSampler{N: 100}, NextSampler: &zerolog.BasicSampler{N: 100},
}, },
}) })
sampled.Debug().Msg("hello world") sampled.Debug().Msg("hello world")
@ -480,8 +453,8 @@ sampled.Debug().Msg("hello world")
```go ```go
type SeverityHook struct{} type SeverityHook struct{}
func (h SeverityHook) Run(e *zlog.Event, level zlog.Level, msg string) { func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
if level != zlog.NoLevel { if level != zerolog.NoLevel {
e.Str("severity", level.String()) e.Str("severity", level.String())
} }
} }
@ -505,7 +478,7 @@ log.Ctx(ctx).Info().Msg("hello world")
### Set as standard logger output ### Set as standard logger output
```go ```go
stdlog := zlog.New(os.Stdout).With(). log := zerolog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
@ -517,38 +490,14 @@ stdlog.Print("hello world")
// Output: {"foo":"bar","message":"hello world"} // Output: {"foo":"bar","message":"hello world"}
``` ```
### context.Context integration
The `Logger` instance could be attached to `context.Context` values with `logger.WithContext(ctx)`
and extracted from it using `zerolog.Ctx(ctx)`.
Example to add logger to context:
```go
// this code attach logger instance to context fields
ctx := context.Background()
logger := zerolog.New(os.Stdout)
ctx = logger.WithContext(ctx)
someFunc(ctx)
```
Extracting logger from context:
```go
func someFunc(ctx context.Context) {
// get logger from context. if it's nill, then `zerolog.DefaultContextLogger` is returned,
// if `DefaultContextLogger` is nil, then disabled logger returned.
logger := zerolog.Ctx(ctx)
logger.Info().Msg("Hello")
}
```
### Integration with `net/http` ### Integration with `net/http`
The `tuxpa.in/a/zlog/hlog` package provides some helpers to integrate zlog with `http.Handler`. The `github.com/rs/zerolog/hlog` package provides some helpers to integrate zerolog 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 := zlog.New(os.Stdout).With(). log := zerolog.New(os.Stdout).With().
Timestamp(). Timestamp().
Str("role", "my-service"). Str("role", "my-service").
Str("host", host). Str("host", host).
@ -595,15 +544,15 @@ if err := http.ListenAndServe(":8080", nil); err != nil {
``` ```
## Multiple Log Output ## Multiple Log Output
`zlog.MultiLevelWriter` may be used to send the log message to multiple outputs. `zerolog.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 := zlog.ConsoleWriter{Out: os.Stdout} consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout}
multi := zlog.MultiLevelWriter(consoleWriter, os.Stdout) multi := zerolog.MultiLevelWriter(consoleWriter, os.Stdout)
logger := zlog.New(multi).With().Timestamp().Logger() logger := zerolog.New(multi).With().Timestamp().Logger()
logger.Info().Msg("Hello World!") logger.Info().Msg("Hello World!")
} }
@ -618,16 +567,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).
* `zlog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zlog.Disabled` to disable logging altogether (quiet mode). * `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zerolog.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. * `zerolog.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. * `zerolog.TimestampFieldName`: Can be set to customize `Timestamp` field name.
* `zlog.LevelFieldName`: Can be set to customize level field name. * `zerolog.LevelFieldName`: Can be set to customize level field name.
* `zlog.MessageFieldName`: Can be set to customize message field name. * `zerolog.MessageFieldName`: Can be set to customize message field name.
* `zlog.ErrorFieldName`: Can be set to customize `Err` field name. * `zerolog.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. * `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.DurationFieldUnit`: Can be set to customize the unit for time.Duration type fields added by `Dur` (default: `time.Millisecond`). * `zerolog.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`). * `zerolog.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. * `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.
## Field Types ## Field Types
@ -641,10 +590,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 `zlog.ErrorFieldName` field name. * `Err`: Takes an `error` and renders it as a string using the `zerolog.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 `zlog.TimestampFieldName` field name, formatted using `zlog.TimeFieldFormat`. * `Timestamp`: Inserts a timestamp field with `zerolog.TimestampFieldName` field name, formatted using `zerolog.TimeFieldFormat`.
* `Time`: Adds a field with time formatted with `zlog.TimeFieldFormat`. * `Time`: Adds a field with time formatted with `zerolog.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`)
@ -655,24 +604,20 @@ Most fields are also available in the slice format (`Strs` for `[]string`, `Errs
## Binary Encoding ## Binary Encoding
<<<<<<< HEAD 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:
=======
In addition to the default JSON encoding, `zerolog` can produce binary logs using [CBOR](https://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows:
>>>>>>> github
```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 zlog library is [CSD](https://github.com/toravir/csd/). with zerolog library is [CSD](https://github.com/toravir/csd/).
## Related Projects ## Related Projects
* [grpc-zlog](https://github.com/cheapRoc/grpc-zlog): Implementation of `grpclog.LoggerV2` interface using `zlog` * [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 `zlog` * [overlog](https://github.com/Trendyol/overlog): Implementation of `Mapped Diagnostic Context` interface using `zerolog`
* [zlogr](https://github.com/go-logr/zlogr): Implementation of `logr.LogSink` interface using `zlog` * [zerologr](https://github.com/go-logr/zerologr): Implementation of `logr.LogSink` interface using `zerolog`
## Benchmarks ## Benchmarks
@ -688,7 +633,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 zlog. There are a few Go logging benchmarks and comparisons that include zerolog.
* [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)
@ -699,7 +644,7 @@ Log a message and 10 fields:
| Library | Time | Bytes Allocated | Objects Allocated | | Library | Time | Bytes Allocated | Objects Allocated |
| :--- | :---: | :---: | :---: | | :--- | :---: | :---: | :---: |
| zlog | 767 ns/op | 552 B/op | 6 allocs/op | | zerolog | 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 |
@ -712,7 +657,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 |
| :--- | :---: | :---: | :---: | | :--- | :---: | :---: | :---: |
| zlog | 52 ns/op | 0 B/op | 0 allocs/op | | zerolog | 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 |
@ -725,7 +670,7 @@ Log a static string, without any context or `printf`-style templating:
| Library | Time | Bytes Allocated | Objects Allocated | | Library | Time | Bytes Allocated | Objects Allocated |
| :--- | :---: | :---: | :---: | | :--- | :---: | :---: | :---: |
| zlog | 50 ns/op | 0 B/op | 0 allocs/op | | zerolog | 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 |
@ -737,10 +682,10 @@ Log a static string, without any context or `printf`-style templating:
## Caveats ## Caveats
Note that zlog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON: Note that zerolog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON:
```go ```go
logger := zlog.New(os.Stderr).With().Timestamp().Logger() logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
logger.Info(). logger.Info().
Timestamp(). Timestamp().
Msg("dup") Msg("dup")

View File

@ -1,4 +1,4 @@
package zlog package zerolog
import ( import (
"net" "net"
@ -57,7 +57,7 @@ func (a *Array) write(dst []byte) []byte {
} }
// Object marshals an object that implement the LogObjectMarshaler // Object marshals an object that implement the LogObjectMarshaler
// interface and appends it to the array. // interface and append append it to the array.
func (a *Array) Object(obj LogObjectMarshaler) *Array { func (a *Array) Object(obj LogObjectMarshaler) *Array {
e := Dict() e := Dict()
obj.MarshalZerologObject(e) obj.MarshalZerologObject(e)
@ -67,19 +67,19 @@ func (a *Array) Object(obj LogObjectMarshaler) *Array {
return a return a
} }
// Str appends the val as a string to the array. // Str append append the val as a string to the array.
func (a *Array) Str(val string) *Array { func (a *Array) Str(val string) *Array {
a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), val) a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), val)
return a return a
} }
// Bytes appends the val as a string to the array. // Bytes append append the val as a string to the array.
func (a *Array) Bytes(val []byte) *Array { func (a *Array) Bytes(val []byte) *Array {
a.buf = enc.AppendBytes(enc.AppendArrayDelim(a.buf), val) a.buf = enc.AppendBytes(enc.AppendArrayDelim(a.buf), val)
return a return a
} }
// Hex appends the val as a hex string to the array. // Hex append append the val as a hex string to the array.
func (a *Array) Hex(val []byte) *Array { func (a *Array) Hex(val []byte) *Array {
a.buf = enc.AppendHex(enc.AppendArrayDelim(a.buf), val) a.buf = enc.AppendHex(enc.AppendArrayDelim(a.buf), val)
return a return a
@ -115,97 +115,97 @@ func (a *Array) Err(err error) *Array {
return a return a
} }
// Bool appends the val as a bool to the array. // Bool append append the val as a bool to the array.
func (a *Array) Bool(b bool) *Array { func (a *Array) Bool(b bool) *Array {
a.buf = enc.AppendBool(enc.AppendArrayDelim(a.buf), b) a.buf = enc.AppendBool(enc.AppendArrayDelim(a.buf), b)
return a return a
} }
// Int appends i as a int to the array. // Int append append i as a int to the array.
func (a *Array) Int(i int) *Array { func (a *Array) Int(i int) *Array {
a.buf = enc.AppendInt(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendInt(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Int8 appends i as a int8 to the array. // Int8 append append i as a int8 to the array.
func (a *Array) Int8(i int8) *Array { func (a *Array) Int8(i int8) *Array {
a.buf = enc.AppendInt8(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendInt8(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Int16 appends i as a int16 to the array. // Int16 append append i as a int16 to the array.
func (a *Array) Int16(i int16) *Array { func (a *Array) Int16(i int16) *Array {
a.buf = enc.AppendInt16(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendInt16(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Int32 appends i as a int32 to the array. // Int32 append append i as a int32 to the array.
func (a *Array) Int32(i int32) *Array { func (a *Array) Int32(i int32) *Array {
a.buf = enc.AppendInt32(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendInt32(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Int64 appends i as a int64 to the array. // Int64 append append i as a int64 to the array.
func (a *Array) Int64(i int64) *Array { func (a *Array) Int64(i int64) *Array {
a.buf = enc.AppendInt64(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendInt64(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Uint appends i as a uint to the array. // Uint append append i as a uint to the array.
func (a *Array) Uint(i uint) *Array { func (a *Array) Uint(i uint) *Array {
a.buf = enc.AppendUint(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendUint(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Uint8 appends i as a uint8 to the array. // Uint8 append append i as a uint8 to the array.
func (a *Array) Uint8(i uint8) *Array { func (a *Array) Uint8(i uint8) *Array {
a.buf = enc.AppendUint8(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendUint8(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Uint16 appends i as a uint16 to the array. // Uint16 append append i as a uint16 to the array.
func (a *Array) Uint16(i uint16) *Array { func (a *Array) Uint16(i uint16) *Array {
a.buf = enc.AppendUint16(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendUint16(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Uint32 appends i as a uint32 to the array. // Uint32 append append i as a uint32 to the array.
func (a *Array) Uint32(i uint32) *Array { func (a *Array) Uint32(i uint32) *Array {
a.buf = enc.AppendUint32(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendUint32(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Uint64 appends i as a uint64 to the array. // Uint64 append append i as a uint64 to the array.
func (a *Array) Uint64(i uint64) *Array { func (a *Array) Uint64(i uint64) *Array {
a.buf = enc.AppendUint64(enc.AppendArrayDelim(a.buf), i) a.buf = enc.AppendUint64(enc.AppendArrayDelim(a.buf), i)
return a return a
} }
// Float32 appends f as a float32 to the array. // Float32 append append f as a float32 to the array.
func (a *Array) Float32(f float32) *Array { func (a *Array) Float32(f float32) *Array {
a.buf = enc.AppendFloat32(enc.AppendArrayDelim(a.buf), f) a.buf = enc.AppendFloat32(enc.AppendArrayDelim(a.buf), f)
return a return a
} }
// Float64 appends f as a float64 to the array. // Float64 append append f as a float64 to the array.
func (a *Array) Float64(f float64) *Array { func (a *Array) Float64(f float64) *Array {
a.buf = enc.AppendFloat64(enc.AppendArrayDelim(a.buf), f) a.buf = enc.AppendFloat64(enc.AppendArrayDelim(a.buf), f)
return a return a
} }
// Time appends t formatted as string using zlog.TimeFieldFormat. // Time append append t formatted as string using zerolog.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
} }
// Dur appends d to the array. // Dur append append d to the array.
func (a *Array) Dur(d time.Duration) *Array { func (a *Array) Dur(d time.Duration) *Array {
a.buf = enc.AppendDuration(enc.AppendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger) a.buf = enc.AppendDuration(enc.AppendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger)
return a return a
} }
// Interface appends i marshaled using reflection. // Interface append append i marshaled using reflection.
func (a *Array) Interface(i interface{}) *Array { func (a *Array) Interface(i interface{}) *Array {
if obj, ok := i.(LogObjectMarshaler); ok { if obj, ok := i.(LogObjectMarshaler); ok {
return a.Object(obj) return a.Object(obj)

View File

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

View File

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

View File

@ -1,6 +1,6 @@
// +build binary_log // +build binary_log
package zlog package zerolog
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 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: 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:
> 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. > 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.
## Solution ## Solution
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. 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.
## 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 `zlog.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 `zerolog.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 tuxpa.in/a/zlog/cmd/lint module github.com/rs/zerolog/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 zlog to recursively ignored packages // add zerolog to recursively ignored packages
recursivelyIgnoredPkgs = append(recursivelyIgnoredPkgs, "tuxpa.in/a/zlog") recursivelyIgnoredPkgs = append(recursivelyIgnoredPkgs, "github.com/rs/zerolog")
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 tuxpa.in/a/zlog.Event type // get the github.com/rs/zerolog.Event type
event := getEvent(p) event := getEvent(p)
if event == nil { if event == nil {
fmt.Fprintln(os.Stderr, "Error: tuxpa.in/a/zlog.Event declaration not found, maybe zlog is not imported in the scanned package?") fmt.Fprintln(os.Stderr, "Error: github.com/rs/zerolog.Event declaration not found, maybe zerolog is not imported in the scanned package?")
os.Exit(1) os.Exit(1)
} }
// get all selections (function calls) with the tuxpa.in/a/zlog.Event (or pointer) receiver // get all selections (function calls) with the github.com/rs/zerolog.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(), "tuxpa.in/a/zlog") { if strings.HasSuffix(pkg.Pkg.Path(), "github.com/rs/zerolog") {
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,40 +0,0 @@
# Zerolog PrettyLog
This is a basic CLI utility that will colorize and pretty print your structured JSON logs.
## Usage
You can compile it or run it directly. The only issue is that by default Zerolog does not output to `stdout`
but rather to `stderr` so we must pipe `stderr` stream to this CLI tool.
### Linux
These commands will redirect `stderr` to our `prettylog` tool and `stdout` will remain unaffected.
1. Compiled version
```shell
some_program_with_zerolog 2> >(prettylog)
```
2. Run it directly with `go run`
```shell
some_program_with_zerolog 2> >(go run cmd/prettylog/prettylog.go)
```
### Windows
These commands will redirect `stderr` to `stdout` and then pipe it to our `prettylog` tool.
1. Compiled version
```shell
some_program_with_zerolog 2>&1 | prettylog
```
2. Run it directly with `go run`
```shell
some_program_with_zerolog 2>&1 | go run cmd/prettylog/prettylog.go
```

View File

@ -1,26 +0,0 @@
package main
import (
"fmt"
"io"
"os"
"tuxpa.in/a/zlog"
)
func isInputFromPipe() bool {
fileInfo, _ := os.Stdin.Stat()
return fileInfo.Mode()&os.ModeCharDevice == 0
}
func main() {
if !isInputFromPipe() {
fmt.Println("The command is intended to work with pipes.")
fmt.Println("Usage: app_with_zerolog | 2> >(prettylog)")
os.Exit(1)
return
}
writer := zlog.NewConsoleWriter()
_, _ = io.Copy(writer, os.Stdin)
}

View File

@ -1,4 +1,4 @@
package zlog package zerolog
import ( import (
"bytes" "bytes"
@ -74,8 +74,6 @@ type ConsoleWriter struct {
FormatFieldValue Formatter FormatFieldValue Formatter
FormatErrFieldName Formatter FormatErrFieldName Formatter
FormatErrFieldValue Formatter FormatErrFieldValue Formatter
FormatExtra func(map[string]interface{}, *bytes.Buffer) error
} }
// NewConsoleWriter creates and initializes a new ConsoleWriter. // NewConsoleWriter creates and initializes a new ConsoleWriter.
@ -130,18 +128,10 @@ func (w ConsoleWriter) Write(p []byte) (n int, err error) {
w.writeFields(evt, buf) w.writeFields(evt, buf)
if w.FormatExtra != nil {
err = w.FormatExtra(evt, buf)
if err != nil {
return n, err
}
}
err = buf.WriteByte('\n') err = buf.WriteByte('\n')
if err != nil { if err != nil {
return n, err return n, err
} }
_, err = buf.WriteTo(w.Out) _, err = buf.WriteTo(w.Out)
return len(p), err return len(p), err
} }
@ -231,7 +221,7 @@ func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer
case json.Number: case json.Number:
buf.WriteString(fv(fValue)) buf.WriteString(fv(fValue))
default: default:
b, err := InterfaceMarshalFunc(fValue) b, err := json.Marshal(fValue)
if err != nil { if err != nil {
fmt.Fprintf(buf, colorize("[error: %v]", colorRed, w.NoColor), err) fmt.Fprintf(buf, colorize("[error: %v]", colorRed, w.NoColor), err)
} else { } else {
@ -337,31 +327,27 @@ func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
t := "<nil>" t := "<nil>"
switch tt := i.(type) { switch tt := i.(type) {
case string: case string:
ts, err := time.ParseInLocation(TimeFieldFormat, tt, time.Local) ts, err := time.Parse(TimeFieldFormat, tt)
if err != nil { if err != nil {
t = tt t = tt
} else { } else {
t = ts.Local().Format(timeFormat) t = ts.Format(timeFormat)
} }
case json.Number: case json.Number:
i, err := tt.Int64() i, err := tt.Int64()
if err != nil { if err != nil {
t = tt.String() t = tt.String()
} else { } else {
var sec, nsec int64 var sec, nsec int64 = i, 0
switch TimeFieldFormat { switch TimeFieldFormat {
case TimeFormatUnixNano:
sec, nsec = 0, i
case TimeFormatUnixMicro:
sec, nsec = 0, int64(time.Duration(i)*time.Microsecond)
case TimeFormatUnixMs: case TimeFormatUnixMs:
sec, nsec = 0, int64(time.Duration(i)*time.Millisecond) nsec = int64(time.Duration(i) * time.Millisecond)
default: sec = 0
sec, nsec = i, 0 case TimeFormatUnixMicro:
nsec = int64(time.Duration(i) * time.Microsecond)
sec = 0
} }
ts := time.Unix(sec, nsec).UTC()
ts := time.Unix(sec, nsec)
t = ts.Format(timeFormat) t = ts.Format(timeFormat)
} }
} }
@ -389,7 +375,7 @@ func consoleDefaultFormatLevel(noColor bool) Formatter {
case LevelPanicValue: case LevelPanicValue:
l = colorize(colorize("PNC", colorRed, noColor), colorBold, noColor) l = colorize(colorize("PNC", colorRed, noColor), colorBold, noColor)
default: default:
l = colorize(ll, colorBold, noColor) l = colorize("???", colorBold, noColor)
} }
} else { } else {
if i == nil { if i == nil {

View File

@ -1,4 +1,4 @@
package zlog_test package zerolog_test
import ( import (
"bytes" "bytes"
@ -9,39 +9,39 @@ import (
"testing" "testing"
"time" "time"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
) )
func ExampleConsoleWriter() { func ExampleConsoleWriter() {
log := zlog.New(zlog.ConsoleWriter{Out: os.Stdout, NoColor: true}) log := zerolog.New(zerolog.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 := zlog.ConsoleWriter{Out: os.Stdout, NoColor: true} out := zerolog.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 := zlog.New(out) log := zerolog.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 := zlog.NewConsoleWriter() out := zerolog.NewConsoleWriter()
out.NoColor = true // For testing purposes only out.NoColor = true // For testing purposes only
log := zlog.New(out) log := zerolog.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 := zlog.NewConsoleWriter( out := zerolog.NewConsoleWriter(
func(w *zlog.ConsoleWriter) { func(w *zerolog.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 := zlog.New(out) log := zerolog.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 := zlog.New(zlog.ConsoleWriter{Out: buf, NoColor: true}) log := zerolog.New(zerolog.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 := zlog.ConsoleWriter{Out: buf, NoColor: true, PartsOrder: []string{"foo"}} w := zerolog.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 := zlog.ConsoleWriter{Out: buf, NoColor: false} w := zerolog.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,16 +106,15 @@ 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 := zlog.ConsoleWriter{Out: buf, NoColor: true} w := zerolog.ConsoleWriter{Out: buf, NoColor: true}
ts := time.Unix(0, 0) d := time.Unix(0, 0).UTC().Format(time.RFC3339)
d := ts.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"}`))
if err != nil { if err != nil {
t.Errorf("Unexpected error when writing output: %s", err) t.Errorf("Unexpected error when writing output: %s", err)
} }
expectedOutput := ts.Format(time.Kitchen) + " DBG Foobar foo=bar\n" expectedOutput := "12:00AM DBG Foobar foo=bar\n"
actualOutput := buf.String() actualOutput := buf.String()
if actualOutput != expectedOutput { if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
@ -123,21 +122,21 @@ 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 := zlog.TimeFieldFormat of := zerolog.TimeFieldFormat
defer func() { defer func() {
zlog.TimeFieldFormat = of zerolog.TimeFieldFormat = of
}() }()
zlog.TimeFieldFormat = zlog.TimeFormatUnix zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zlog.ConsoleWriter{Out: buf, TimeFormat: time.StampMilli, NoColor: true} w := zerolog.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 {
t.Errorf("Unexpected error when writing output: %s", err) t.Errorf("Unexpected error when writing output: %s", err)
} }
expectedOutput := time.Unix(1234, 0).Format(time.StampMilli) + " DBG Foobar foo=bar\n" expectedOutput := "Jan 1 00:20:34.000 DBG Foobar foo=bar\n"
actualOutput := buf.String() actualOutput := buf.String()
if actualOutput != expectedOutput { if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
@ -145,21 +144,21 @@ 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 := zlog.TimeFieldFormat of := zerolog.TimeFieldFormat
defer func() { defer func() {
zlog.TimeFieldFormat = of zerolog.TimeFieldFormat = of
}() }()
zlog.TimeFieldFormat = zlog.TimeFormatUnixMs zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zlog.ConsoleWriter{Out: buf, TimeFormat: time.StampMilli, NoColor: true} w := zerolog.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 {
t.Errorf("Unexpected error when writing output: %s", err) t.Errorf("Unexpected error when writing output: %s", err)
} }
expectedOutput := time.Unix(1234, 567000000).Format(time.StampMilli) + " DBG Foobar foo=bar\n" expectedOutput := "Jan 1 00:20:34.567 DBG Foobar foo=bar\n"
actualOutput := buf.String() actualOutput := buf.String()
if actualOutput != expectedOutput { if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
@ -167,21 +166,21 @@ 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 := zlog.TimeFieldFormat of := zerolog.TimeFieldFormat
defer func() { defer func() {
zlog.TimeFieldFormat = of zerolog.TimeFieldFormat = of
}() }()
zlog.TimeFieldFormat = zlog.TimeFormatUnixMicro zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMicro
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
w := zlog.ConsoleWriter{Out: buf, TimeFormat: time.StampMicro, NoColor: true} w := zerolog.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 {
t.Errorf("Unexpected error when writing output: %s", err) t.Errorf("Unexpected error when writing output: %s", err)
} }
expectedOutput := time.Unix(1234, 567891000).Format(time.StampMicro) + " DBG Foobar foo=bar\n" expectedOutput := "Jan 1 00:20:34.567891 DBG Foobar foo=bar\n"
actualOutput := buf.String() actualOutput := buf.String()
if actualOutput != expectedOutput { if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
@ -190,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 := zlog.ConsoleWriter{Out: buf, NoColor: true} w := zerolog.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 {
@ -206,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 := zlog.ConsoleWriter{Out: buf, NoColor: true} w := zerolog.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 {
@ -222,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 := zlog.ConsoleWriter{Out: buf, NoColor: false} w := zerolog.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 {
@ -238,10 +237,9 @@ 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 := zlog.ConsoleWriter{Out: buf, NoColor: true} w := zerolog.ConsoleWriter{Out: buf, NoColor: true}
ts := time.Unix(0, 0) d := time.Unix(0, 0).UTC().Format(time.RFC3339)
d := ts.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"}`
// t.Log(evt) // t.Log(evt)
@ -250,7 +248,7 @@ func TestConsoleWriter(t *testing.T) {
t.Errorf("Unexpected error when writing output: %s", err) t.Errorf("Unexpected error when writing output: %s", err)
} }
expectedOutput := ts.Format(time.Kitchen) + " ERR Foobar error=Error aaa=bbb\n" expectedOutput := "12:00AM ERR Foobar error=Error aaa=bbb\n"
actualOutput := buf.String() actualOutput := buf.String()
if actualOutput != expectedOutput { if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
@ -259,15 +257,14 @@ 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 := zlog.ConsoleWriter{Out: buf, NoColor: true} w := zerolog.ConsoleWriter{Out: buf, NoColor: true}
cwd, err := os.Getwd() cwd, err := os.Getwd()
if err != nil { if err != nil {
t.Fatalf("Cannot get working directory: %s", err) t.Fatalf("Cannot get working directory: %s", err)
} }
ts := time.Unix(0, 0) d := time.Unix(0, 0).UTC().Format(time.RFC3339)
d := ts.UTC().Format(time.RFC3339)
evt := `{"time": "` + d + `", "level": "debug", "message": "Foobar", "foo": "bar", "caller": "` + cwd + `/foo/bar.go"}` evt := `{"time": "` + d + `", "level": "debug", "message": "Foobar", "foo": "bar", "caller": "` + cwd + `/foo/bar.go"}`
// t.Log(evt) // t.Log(evt)
@ -276,7 +273,7 @@ func TestConsoleWriter(t *testing.T) {
t.Errorf("Unexpected error when writing output: %s", err) t.Errorf("Unexpected error when writing output: %s", err)
} }
expectedOutput := ts.Format(time.Kitchen) + " DBG foo/bar.go > Foobar foo=bar\n" expectedOutput := "12:00AM DBG foo/bar.go > Foobar foo=bar\n"
actualOutput := buf.String() actualOutput := buf.String()
if actualOutput != expectedOutput { if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
@ -285,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 := zlog.ConsoleWriter{Out: buf, NoColor: true} w := zerolog.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)
@ -306,10 +303,9 @@ 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 := zlog.ConsoleWriter{Out: buf, NoColor: true, TimeFormat: time.RFC3339} w := zerolog.ConsoleWriter{Out: buf, NoColor: true, TimeFormat: time.RFC3339}
ts := time.Unix(0, 0) d := time.Unix(0, 0).UTC().Format(time.RFC3339)
d := ts.UTC().Format(time.RFC3339)
evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}` evt := `{"time": "` + d + `", "level": "info", "message": "Foobar"}`
_, err := w.Write([]byte(evt)) _, err := w.Write([]byte(evt))
@ -317,7 +313,7 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Errorf("Unexpected error when writing output: %s", err) t.Errorf("Unexpected error when writing output: %s", err)
} }
expectedOutput := ts.Format(time.RFC3339) + " INF Foobar\n" expectedOutput := "1970-01-01T00:00:00Z INF Foobar\n"
actualOutput := buf.String() actualOutput := buf.String()
if actualOutput != expectedOutput { if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
@ -326,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 := zlog.ConsoleWriter{Out: buf, NoColor: true, PartsOrder: []string{"message", "level"}} w := zerolog.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))
@ -343,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 := zlog.ConsoleWriter{Out: buf, NoColor: true, PartsExclude: []string{"time"}} w := zerolog.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"}`
@ -361,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 := zlog.ConsoleWriter{Out: buf, NoColor: true, FieldsExclude: []string{"foo"}} w := zerolog.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))
@ -375,55 +371,6 @@ func TestConsoleWriterConfiguration(t *testing.T) {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput) t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
} }
}) })
t.Run("Sets FormatExtra", func(t *testing.T) {
buf := &bytes.Buffer{}
w := zlog.ConsoleWriter{
Out: buf, NoColor: true, PartsOrder: []string{"level", "message"},
FormatExtra: func(evt map[string]interface{}, buf *bytes.Buffer) error {
buf.WriteString("\nAdditional stacktrace")
return nil
},
}
evt := `{"level": "info", "message": "Foobar"}`
_, err := w.Write([]byte(evt))
if err != nil {
t.Errorf("Unexpected error when writing output: %s", err)
}
expectedOutput := "INF Foobar\nAdditional stacktrace\n"
actualOutput := buf.String()
if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
}
})
t.Run("Uses local time for console writer without time zone", func(t *testing.T) {
// Regression test for issue #483 (check there for more details)
timeFormat := "2006-01-02 15:04:05"
expectedOutput := "2022-10-20 20:24:50 INF Foobar\n"
evt := `{"time": "2022-10-20 20:24:50", "level": "info", "message": "Foobar"}`
of := zlog.TimeFieldFormat
defer func() {
zlog.TimeFieldFormat = of
}()
zlog.TimeFieldFormat = timeFormat
buf := &bytes.Buffer{}
w := zlog.ConsoleWriter{Out: buf, NoColor: true, TimeFormat: timeFormat}
_, err := w.Write([]byte(evt))
if err != nil {
t.Errorf("Unexpected error when writing output: %s", err)
}
actualOutput := buf.String()
if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
}
})
} }
func BenchmarkConsoleWriter(b *testing.B) { func BenchmarkConsoleWriter(b *testing.B) {
@ -432,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 := zlog.ConsoleWriter{Out: ioutil.Discard, NoColor: false} w := zerolog.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 zlog package zerolog
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 zlog.Arr() to create the array or pass a type that // Use zerolog.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)
@ -329,9 +329,8 @@ func (ts timestampHook) Run(e *Event, level Level, msg string) {
var th = timestampHook{} var th = timestampHook{}
// Timestamp adds the current local time to the logger context with the "time" key, formatted using zlog.TimeFieldFormat. // Timestamp adds the current local time as UNIX timestamp to the logger context with the "time" key.
// To customize the key name, change zlog.TimestampFieldName. // To customize the key name, change zerolog.TimestampFieldName.
// To customize the time format, change zlog.TimeFieldFormat.
// //
// 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 {
@ -339,13 +338,13 @@ func (c Context) Timestamp() Context {
return c return c
} }
// Time adds the field key with t formated as string using zlog.TimeFieldFormat. // Time adds the field key with t formated as string using zerolog.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 zlog.TimeFieldFormat. // Times adds the field key with t formated as string using zerolog.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
@ -395,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 zlog.CallerFieldName key. // Caller adds the file:line of the caller with the zerolog.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 zlog.CallerFieldName key. // CallerWithSkipFrameCount adds the file:line of the caller with the zerolog.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 {

23
ctx.go
View File

@ -1,4 +1,4 @@
package zlog package zerolog
import ( import (
"context" "context"
@ -14,25 +14,24 @@ func init() {
type ctxKey struct{} type ctxKey struct{}
// WithContext returns a copy of ctx with the receiver attached. The Logger // WithContext returns a copy of ctx with l associated. If an instance of Logger
// attached to the provided Context (if any) will not be effected. If the // is already in the context, the context is not updated.
// receiver's log level is Disabled it will only be attached to the returned
// Context if the provided Context has a previously attached Logger. If the
// provided Context has no attached Logger, a Disabled Logger will not be
// attached.
// //
// Note: to modify the existing Logger attached to a Context (instead of // For instance, to add a field to an existing logger in the context, use this
// replacing it in a new Context), use UpdateContext with the following
// notation: // notation:
// //
// ctx := r.Context() // ctx := r.Context()
// l := zlog.Ctx(ctx) // l := zerolog.Ctx(ctx)
// l.UpdateContext(func(c Context) Context { // l.UpdateContext(func(c Context) Context {
// return c.Str("bar", "baz") // return c.Str("bar", "baz")
// }) // })
//
func (l Logger) WithContext(ctx context.Context) context.Context { func (l Logger) WithContext(ctx context.Context) context.Context {
if _, ok := ctx.Value(ctxKey{}).(*Logger); !ok && l.level == Disabled { if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
if lp == &l {
// Do not store same logger.
return ctx
}
} else if l.level == Disabled {
// Do not store disabled logger. // Do not store disabled logger.
return ctx return ctx
} }

View File

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

View File

@ -8,7 +8,7 @@ import (
"sync" "sync"
"time" "time"
"tuxpa.in/a/zlog/diode/internal/diodes" "github.com/rs/zerolog/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 := zlog.New(wr) // log := zerolog.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 zlog so we can't hold it passed this call, hence the // p is pooled in zerolog 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"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/diode" "github.com/rs/zerolog/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 := zlog.New(w) log := zerolog.New(w)
log.Print("test") log.Print("test")
w.Close() w.Close()

View File

@ -9,9 +9,9 @@ import (
"testing" "testing"
"time" "time"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/diode" "github.com/rs/zerolog/diode"
"tuxpa.in/a/zlog/internal/cbor" "github.com/rs/zerolog/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 := zlog.New(w) log := zerolog.New(w)
log.Print("test") log.Print("test")
w.Close() w.Close()
@ -30,14 +30,6 @@ func TestNewWriter(t *testing.T) {
} }
} }
func TestClose(t *testing.T) {
buf := bytes.Buffer{}
w := diode.NewWriter(&buf, 1000, 0, func(missed int) {})
log := zlog.New(w)
log.Print("test")
w.Close()
}
func Benchmark(b *testing.B) { func Benchmark(b *testing.B) {
log.SetOutput(ioutil.Discard) log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stderr) defer log.SetOutput(os.Stderr)
@ -48,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 := zlog.New(w) log := zerolog.New(w)
defer w.Close() defer w.Close()
b.SetParallelism(1000) b.SetParallelism(1000)

View File

@ -39,12 +39,7 @@ func NewWaiter(d Diode, opts ...WaiterConfigOption) *Waiter {
go func() { go func() {
<-w.ctx.Done() <-w.ctx.Done()
// Mutex is strictly necessary here to avoid a race in Next() (between
// w.isDone() and w.c.Wait()) and w.c.Broadcast() here.
w.mu.Lock()
w.c.Broadcast() w.c.Broadcast()
w.mu.Unlock()
}() }()
return w return w

View File

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

View File

@ -1,11 +1,11 @@
// +build binary_log // +build binary_log
package zlog package zerolog
// This file contains bindings to do binary encoding. // This file contains bindings to do binary encoding.
import ( import (
"tuxpa.in/a/zlog/internal/cbor" "github.com/rs/zerolog/internal/cbor"
) )
var ( var (
@ -24,9 +24,6 @@ func init() {
func appendJSON(dst []byte, j []byte) []byte { func appendJSON(dst []byte, j []byte) []byte {
return cbor.AppendEmbeddedJSON(dst, j) return cbor.AppendEmbeddedJSON(dst, j)
} }
func appendCBOR(dst []byte, c []byte) []byte {
return cbor.AppendEmbeddedCBOR(dst, c)
}
// decodeIfBinaryToString - converts a binary formatted log msg to a // decodeIfBinaryToString - converts a binary formatted log msg to a
// JSON formatted String Log message. // JSON formatted String Log message.

View File

@ -1,14 +1,12 @@
//go:build !binary_log
// +build !binary_log // +build !binary_log
package zlog package zerolog
// 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 (
"encoding/base64" "github.com/rs/zerolog/internal/json"
"tuxpa.in/a/zlog/internal/json"
) )
var ( var (
@ -27,17 +25,6 @@ func init() {
func appendJSON(dst []byte, j []byte) []byte { func appendJSON(dst []byte, j []byte) []byte {
return append(dst, j...) return append(dst, j...)
} }
func appendCBOR(dst []byte, cbor []byte) []byte {
dst = append(dst, []byte("\"data:application/cbor;base64,")...)
l := len(dst)
enc := base64.StdEncoding
n := enc.EncodedLen(len(cbor))
for i := 0; i < n; i++ {
dst = append(dst, '.')
}
enc.Encode(dst[l:], cbor)
return append(dst, '"')
}
func decodeIfBinaryToString(in []byte) string { func decodeIfBinaryToString(in []byte) string {
return string(in) return string(in)

View File

@ -1,4 +1,4 @@
package zlog package zerolog
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, "zlog: could not write event: %v\n", err) fmt.Fprintf(os.Stderr, "zerolog: 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 zlog.Dict() to create the dictionary. // Use zerolog.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 zlog.Arr() to create the array or pass a type that // Use zerolog.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 {
@ -318,18 +318,6 @@ func (e *Event) RawJSON(key string, b []byte) *Event {
return e return e
} }
// RawCBOR adds already encoded CBOR to the log line under key.
//
// No sanity check is performed on b
// Note: The full featureset of CBOR is supported as data will not be mapped to json but stored as data-url
func (e *Event) RawCBOR(key string, b []byte) *Event {
if e == nil {
return e
}
e.buf = appendCBOR(enc.AppendKey(e.buf, key), b)
return e
}
// AnErr adds the field key with serialized err to the *Event context. // AnErr adds the field key with serialized err to the *Event context.
// If err is nil, no field is added. // If err is nil, no field is added.
func (e *Event) AnErr(key string, err error) *Event { func (e *Event) AnErr(key string, err error) *Event {
@ -380,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 zlog.ErrorFieldName. // To customize the key name, change zerolog.ErrorFieldName.
// //
// If Stack() has been called before and zlog.ErrorStackMarshaler is defined, // If Stack() has been called before and zerolog.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
// zlog.ErrorStackFieldName. // zerolog.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
@ -652,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 zlog.TimestampFieldName. // To customize the key name, change zerolog.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.
@ -664,7 +652,7 @@ func (e *Event) Timestamp() *Event {
return e return e
} }
// Time adds the field key with t formatted as string using zlog.TimeFieldFormat. // Time adds the field key with t formatted as string using zerolog.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
@ -673,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 zlog.TimeFieldFormat. // Times adds the field key with t formatted as string using zerolog.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
@ -682,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 zlog.DurationFieldUnit. // Dur adds the field key with duration d stored as zerolog.DurationFieldUnit.
// If zlog.DurationFieldInteger is true, durations are rendered as integer // If zerolog.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 {
@ -693,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 zlog.DurationFieldUnit. // Durs adds the field key with duration d stored as zerolog.DurationFieldUnit.
// If zlog.DurationFieldInteger is true, durations are rendered as integer // If zerolog.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 {
@ -719,11 +707,6 @@ func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event {
return e return e
} }
// Any is a wrapper around Event.Interface.
func (e *Event) Any(key string, i interface{}) *Event {
return e.Interface(key, i)
}
// Interface adds the field key with i marshaled using reflection. // Interface adds the field key with i marshaled using reflection.
func (e *Event) Interface(key string, i interface{}) *Event { func (e *Event) Interface(key string, i interface{}) *Event {
if e == nil { if e == nil {
@ -736,15 +719,6 @@ func (e *Event) Interface(key string, i interface{}) *Event {
return e return e
} }
// Type adds the field key with val's type using reflection.
func (e *Event) Type(key string, val interface{}) *Event {
if e == nil {
return e
}
e.buf = enc.AppendType(enc.AppendKey(e.buf, key), val)
return e
}
// CallerSkipFrame instructs any future Caller calls to skip the specified number of frames. // CallerSkipFrame instructs any future Caller calls to skip the specified number of frames.
// This includes those added via hooks from the context. // This includes those added via hooks from the context.
func (e *Event) CallerSkipFrame(skip int) *Event { func (e *Event) CallerSkipFrame(skip int) *Event {
@ -755,7 +729,7 @@ func (e *Event) CallerSkipFrame(skip int) *Event {
return e return e
} }
// Caller adds the file:line of the caller with the zlog.CallerFieldName key. // Caller adds the file:line of the caller with the zerolog.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 {
@ -770,11 +744,11 @@ func (e *Event) caller(skip int) *Event {
if e == nil { if e == nil {
return e return e
} }
pc, file, line, ok := runtime.Caller(skip + e.skipFrame) _, file, line, ok := runtime.Caller(skip + e.skipFrame)
if !ok { if !ok {
return e return e
} }
e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), CallerMarshalFunc(pc, file, line)) e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), CallerMarshalFunc(file, line))
return e return e
} }

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package zlog package zerolog
import ( import (
"encoding/json" "encoding/json"
@ -19,10 +19,6 @@ const (
// TimeFormatUnixMicro defines a time format that makes time fields to be // TimeFormatUnixMicro defines a time format that makes time fields to be
// serialized as Unix timestamp integers in microseconds. // serialized as Unix timestamp integers in microseconds.
TimeFormatUnixMicro = "UNIXMICRO" TimeFormatUnixMicro = "UNIXMICRO"
// TimeFormatUnixNano defines a time format that makes time fields to be
// serialized as Unix timestamp integers in nanoseconds.
TimeFormatUnixNano = "UNIXNANO"
) )
var ( var (
@ -65,7 +61,7 @@ var (
CallerSkipFrameCount = 2 CallerSkipFrameCount = 2
// CallerMarshalFunc allows customization of global caller marshaling // CallerMarshalFunc allows customization of global caller marshaling
CallerMarshalFunc = func(pc uintptr, file string, line int) string { CallerMarshalFunc = func(file string, line int) string {
return file + ":" + strconv.Itoa(line) return file + ":" + strconv.Itoa(line)
} }
@ -85,7 +81,7 @@ var (
InterfaceMarshalFunc = json.Marshal InterfaceMarshalFunc = json.Marshal
// TimeFieldFormat defines the time format of the Time field type. If set to // TimeFieldFormat defines the time format of the Time field type. If set to
// TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX // TimeFormatUnix, TimeFormatUnixMs or TimeFormatUnixMicro, the time is formatted as a UNIX
// timestamp as integer. // timestamp as integer.
TimeFieldFormat = time.RFC3339 TimeFieldFormat = time.RFC3339
@ -100,7 +96,7 @@ var (
// set to true. // set to true.
DurationFieldInteger = false DurationFieldInteger = false
// ErrorHandler is called whenever zlog fails to write an event on its // ErrorHandler is called whenever zerolog 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)

8
go.mod
View File

@ -1,12 +1,10 @@
module tuxpa.in/a/zlog module github.com/rs/zerolog
go 1.15 go 1.15
require ( require (
github.com/coreos/go-systemd/v22 v22.5.0 github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534
github.com/mattn/go-colorable v0.1.12 github.com/mattn/go-colorable v0.1.12
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/rs/xid v1.5.0 github.com/rs/xid v1.3.0
github.com/rs/zerolog v1.28.0
golang.org/x/sys v0.0.0-20220915200043-7b5979e65e41 // indirect
) )

15
go.sum
View File

@ -1,6 +1,7 @@
github.com/coreos/go-systemd/v22 v22.3.2 h1:D9/bQk5vlXQFZ6Kwuu6zaiXJ9oTPe68++AzAJc1DzSI=
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534 h1:rtAn27wIbmOGUs7RIbVgPEjb31ehTVniDwPGXyMxm5U=
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
@ -8,12 +9,8 @@ github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/xid v1.3.0 h1:6NjYksEUlhurdVehpc7S7dk6DAmcKv8V9gG0FsVN2U4=
github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc= github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 h1:foEbQz/B0Oz6YIqu/69kfXPYeFQAuuMYFkjaqXzl5Wo=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220915200043-7b5979e65e41 h1:ohgcoMbSofXygzo6AD2I1kz3BFmW1QArPYTtwEM3UXc=
golang.org/x/sys v0.0.0-20220915200043-7b5979e65e41/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

View File

@ -1,6 +1,6 @@
// +build go1.12 // +build go1.12
package zlog package zerolog
// 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 zlog. // Package hlog provides a set of http.Handler helpers for zerolog.
package hlog package hlog
import ( import (
@ -7,19 +7,19 @@ import (
"time" "time"
"github.com/rs/xid" "github.com/rs/xid"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/hlog/internal/mutil" "github.com/rs/zerolog/hlog/internal/mutil"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/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) *zlog.Logger { func FromRequest(r *http.Request) *zerolog.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 zlog.Logger) func(http.Handler) http.Handler { func NewHandler(log zerolog.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 zlog.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 := zlog.Ctx(r.Context()) log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context { log.UpdateContext(func(c zerolog.Context) zerolog.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 := zlog.Ctx(r.Context()) log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context { log.UpdateContext(func(c zerolog.Context) zerolog.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 := zlog.Ctx(r.Context()) log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context { log.UpdateContext(func(c zerolog.Context) zerolog.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 := zlog.Ctx(r.Context()) log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context { log.UpdateContext(func(c zerolog.Context) zerolog.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 := zlog.Ctx(r.Context()) log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context { log.UpdateContext(func(c zerolog.Context) zerolog.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 := zlog.Ctx(r.Context()) log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context { log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str(fieldKey, ref) return c.Str(fieldKey, ref)
}) })
} }
@ -121,20 +121,6 @@ func RefererHandler(fieldKey string) func(next http.Handler) http.Handler {
} }
} }
// ProtoHandler adds the requests protocol version as a field to the context logger
// using fieldKey as field Key.
func ProtoHandler(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 := zlog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context {
return c.Str(fieldKey, r.Proto)
})
next.ServeHTTP(w, r)
})
}
}
type idKey struct{} type idKey struct{}
// IDFromRequest returns the unique id associated to the request if any. // IDFromRequest returns the unique id associated to the request if any.
@ -176,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 := zlog.Ctx(ctx) log := zerolog.Ctx(ctx)
log.UpdateContext(func(c zlog.Context) zlog.Context { log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str(fieldKey, id.String()) return c.Str(fieldKey, id.String())
}) })
} }
@ -195,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 := zlog.Ctx(r.Context()) log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zlog.Context) zlog.Context { log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str(fieldKey, val) return c.Str(fieldKey, val)
}) })
} }

View File

@ -9,8 +9,8 @@ import (
"net/http/httptest" "net/http/httptest"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/hlog" "github.com/rs/zerolog/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() {
zlog.TimestampFunc = func() time.Time { zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.New(os.Stdout).With().
Timestamp(). Timestamp().
Str("role", "my-service"). Str("role", "my-service").
Str("host", "local-hostname"). Str("host", "local-hostname").

View File

@ -1,4 +1,3 @@
//go:build go1.7
// +build go1.7 // +build go1.7
package hlog package hlog
@ -15,8 +14,8 @@ import (
"testing" "testing"
"github.com/rs/xid" "github.com/rs/xid"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/internal/cbor" "github.com/rs/zerolog/internal/cbor"
) )
func decodeIfBinary(out *bytes.Buffer) string { func decodeIfBinary(out *bytes.Buffer) string {
@ -28,7 +27,7 @@ func decodeIfBinary(out *bytes.Buffer) string {
} }
func TestNewHandler(t *testing.T) { func TestNewHandler(t *testing.T) {
log := zlog.New(nil).With(). log := zerolog.New(nil).With().
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
lh := NewHandler(log) lh := NewHandler(log)
@ -50,7 +49,7 @@ func TestURLHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
@ -66,7 +65,7 @@ func TestMethodHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
@ -83,7 +82,7 @@ func TestRequestHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
@ -99,7 +98,7 @@ func TestRemoteAddrHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
@ -115,7 +114,7 @@ func TestRemoteAddrHandlerIPv6(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
@ -133,7 +132,7 @@ func TestUserAgentHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
@ -151,7 +150,7 @@ func TestRefererHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
@ -179,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(zlog.New(out))(h) h = NewHandler(zerolog.New(out))(h)
h.ServeHTTP(httptest.NewRecorder(), r) h.ServeHTTP(httptest.NewRecorder(), r)
} }
@ -194,29 +193,13 @@ func TestCustomHeaderHandler(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
} }
} }
func TestProtoHandler(t *testing.T) {
out := &bytes.Buffer{}
r := &http.Request{
Proto: "test",
}
h := ProtoHandler("proto")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
l := FromRequest(r)
l.Log().Msg("")
}))
h = NewHandler(zlog.New(out))(h)
h.ServeHTTP(nil, r)
if want, got := `{"proto":"test"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want)
}
}
func TestCombinedHandlers(t *testing.T) { func TestCombinedHandlers(t *testing.T) {
out := &bytes.Buffer{} out := &bytes.Buffer{}
r := &http.Request{ r := &http.Request{
@ -227,7 +210,7 @@ func TestCombinedHandlers(t *testing.T) {
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})))) }))))
h = NewHandler(zlog.New(out))(h) h = NewHandler(zerolog.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)
@ -245,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(zlog.New(ioutil.Discard))(h1), "Single": NewHandler(zerolog.New(ioutil.Discard))(h1),
"Combined": NewHandler(zlog.New(ioutil.Discard))(h2), "Combined": NewHandler(zerolog.New(ioutil.Discard))(h2),
"SingleDisabled": NewHandler(zlog.New(ioutil.Discard).Level(zlog.Disabled))(h1), "SingleDisabled": NewHandler(zerolog.New(ioutil.Discard).Level(zerolog.Disabled))(h1),
"CombinedDisabled": NewHandler(zlog.New(ioutil.Discard).Level(zlog.Disabled))(h2), "CombinedDisabled": NewHandler(zerolog.New(ioutil.Discard).Level(zerolog.Disabled))(h2),
} }
for name := range handlers { for name := range handlers {
h := handlers[name] h := handlers[name]
@ -261,13 +244,13 @@ func BenchmarkHandlers(b *testing.B) {
} }
func BenchmarkDataRace(b *testing.B) { func BenchmarkDataRace(b *testing.B) {
log := zlog.New(nil).With(). log := zerolog.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 zlog.Context) zlog.Context { l.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str("bar", "baz") return c.Str("bar", "baz")
}) })
l.Log().Msg("") l.Log().Msg("")

View File

@ -1,4 +1,4 @@
package zlog package zerolog
// 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 zlog package zerolog
import ( import (
"bytes" "bytes"

View File

@ -27,7 +27,6 @@ const (
// Tag Sub-types. // Tag Sub-types.
additionalTypeTimestamp byte = 01 additionalTypeTimestamp byte = 01
additionalTypeEmbeddedCBOR byte = 63
// Extended Tags - from https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml // Extended Tags - from https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml
additionalTypeTagNetworkAddr uint16 = 260 additionalTypeTagNetworkAddr uint16 = 260

View File

@ -5,7 +5,6 @@ package cbor
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"encoding/base64"
"fmt" "fmt"
"io" "io"
"math" "math"
@ -214,31 +213,6 @@ func decodeString(src *bufio.Reader, noQuotes bool) []byte {
} }
return append(result, '"') return append(result, '"')
} }
func decodeStringToDataUrl(src *bufio.Reader, mimeType string) []byte {
pb := readByte(src)
major := pb & maskOutAdditionalType
minor := pb & maskOutMajorType
if major != majorTypeByteString {
panic(fmt.Errorf("Major type is: %d in decodeString", major))
}
length := decodeIntAdditionalType(src, minor)
l := int(length)
enc := base64.StdEncoding
lEnc := enc.EncodedLen(l)
result := make([]byte, len("\"data:;base64,\"")+len(mimeType)+lEnc)
dest := result
u := copy(dest, "\"data:")
dest = dest[u:]
u = copy(dest, mimeType)
dest = dest[u:]
u = copy(dest, ";base64,")
dest = dest[u:]
pbs := readNBytes(src, l)
enc.Encode(dest, pbs)
dest = dest[lEnc:]
dest[0] = '"'
return result
}
func decodeUTF8String(src *bufio.Reader) []byte { func decodeUTF8String(src *bufio.Reader) []byte {
pb := readByte(src) pb := readByte(src)
@ -375,20 +349,6 @@ func decodeTagData(src *bufio.Reader) []byte {
switch minor { switch minor {
case additionalTypeTimestamp: case additionalTypeTimestamp:
return decodeTimeStamp(src) return decodeTimeStamp(src)
case additionalTypeIntUint8:
val := decodeIntAdditionalType(src, minor)
switch byte(val) {
case additionalTypeEmbeddedCBOR:
pb := readByte(src)
dataMajor := pb & maskOutAdditionalType
if dataMajor != majorTypeByteString {
panic(fmt.Errorf("Unsupported embedded Type: %d in decodeEmbeddedCBOR", dataMajor))
}
src.UnreadByte()
return decodeStringToDataUrl(src, "application/cbor")
default:
panic(fmt.Errorf("Unsupported Additional Tag Type: %d in decodeTagData", val))
}
// Tag value is larger than 256 (so uint16). // Tag value is larger than 256 (so uint16).
case additionalTypeIntUint16: case additionalTypeIntUint16:

View File

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

View File

@ -93,25 +93,3 @@ func AppendEmbeddedJSON(dst, s []byte) []byte {
} }
return append(dst, s...) return append(dst, s...)
} }
// AppendEmbeddedCBOR adds a tag and embeds input CBOR as such.
func AppendEmbeddedCBOR(dst, s []byte) []byte {
major := majorTypeTags
minor := additionalTypeEmbeddedCBOR
// Append the TAG to indicate this is Embedded JSON.
dst = append(dst, major|additionalTypeIntUint8)
dst = append(dst, minor)
// Append the CBOR Object as Byte String.
major = majorTypeByteString
l := len(s)
if l <= additionalMax {
lb := byte(l)
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
return append(dst, s...)
}

View File

@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"math" "math"
"net" "net"
"reflect"
) )
// AppendNil inserts a 'Nil' object into the dst byte array. // AppendNil inserts a 'Nil' object into the dst byte array.
@ -439,14 +438,6 @@ func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte {
return AppendEmbeddedJSON(dst, marshaled) return AppendEmbeddedJSON(dst, marshaled)
} }
// AppendType appends the parameter type (as a string) to the input byte slice.
func (e Encoder) AppendType(dst []byte, i interface{}) []byte {
if i == nil {
return e.AppendString(dst, "<nil>")
}
return e.AppendString(dst, reflect.TypeOf(i).String())
}
// AppendIPAddr encodes and inserts an IP Address (IPv4 or IPv6). // AppendIPAddr encodes and inserts an IP Address (IPv4 or IPv6).
func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte { func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte {
dst = append(dst, majorTypeTags|additionalTypeIntUint16) dst = append(dst, majorTypeTags|additionalTypeIntUint16)

View File

@ -6,11 +6,10 @@ import (
) )
const ( const (
// Import from zlog/global.go // Import from zerolog/global.go
timeFormatUnix = "" timeFormatUnix = ""
timeFormatUnixMs = "UNIXMS" timeFormatUnixMs = "UNIXMS"
timeFormatUnixMicro = "UNIXMICRO" timeFormatUnixMicro = "UNIXMICRO"
timeFormatUnixNano = "UNIXNANO"
) )
// AppendTime formats the input time with the given format // AppendTime formats the input time with the given format
@ -23,8 +22,6 @@ func (e Encoder) AppendTime(dst []byte, t time.Time, format string) []byte {
return e.AppendInt64(dst, t.UnixNano()/1000000) return e.AppendInt64(dst, t.UnixNano()/1000000)
case timeFormatUnixMicro: case timeFormatUnixMicro:
return e.AppendInt64(dst, t.UnixNano()/1000) return e.AppendInt64(dst, t.UnixNano()/1000)
case timeFormatUnixNano:
return e.AppendInt64(dst, t.UnixNano())
} }
return append(t.AppendFormat(append(dst, '"'), format), '"') return append(t.AppendFormat(append(dst, '"'), format), '"')
} }
@ -36,11 +33,7 @@ func (Encoder) AppendTimes(dst []byte, vals []time.Time, format string) []byte {
case timeFormatUnix: case timeFormatUnix:
return appendUnixTimes(dst, vals) return appendUnixTimes(dst, vals)
case timeFormatUnixMs: case timeFormatUnixMs:
return appendUnixNanoTimes(dst, vals, 1000000) return appendUnixMsTimes(dst, vals)
case timeFormatUnixMicro:
return appendUnixNanoTimes(dst, vals, 1000)
case timeFormatUnixNano:
return appendUnixNanoTimes(dst, vals, 1)
} }
if len(vals) == 0 { if len(vals) == 0 {
return append(dst, '[', ']') return append(dst, '[', ']')
@ -71,15 +64,15 @@ func appendUnixTimes(dst []byte, vals []time.Time) []byte {
return dst return dst
} }
func appendUnixNanoTimes(dst []byte, vals []time.Time, div int64) []byte { func appendUnixMsTimes(dst []byte, vals []time.Time) []byte {
if len(vals) == 0 { if len(vals) == 0 {
return append(dst, '[', ']') return append(dst, '[', ']')
} }
dst = append(dst, '[') dst = append(dst, '[')
dst = strconv.AppendInt(dst, vals[0].UnixNano()/div, 10) dst = strconv.AppendInt(dst, vals[0].UnixNano()/1000000, 10)
if len(vals) > 1 { if len(vals) > 1 {
for _, t := range vals[1:] { for _, t := range vals[1:] {
dst = strconv.AppendInt(append(dst, ','), t.UnixNano()/div, 10) dst = strconv.AppendInt(append(dst, ','), t.UnixNano()/1000000, 10)
} }
} }
dst = append(dst, ']') dst = append(dst, ']')

View File

@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"math" "math"
"net" "net"
"reflect"
"strconv" "strconv"
) )
@ -370,14 +369,6 @@ func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte {
return append(dst, marshaled...) return append(dst, marshaled...)
} }
// AppendType appends the parameter type (as a string) to the input byte slice.
func (e Encoder) AppendType(dst []byte, i interface{}) []byte {
if i == nil {
return e.AppendString(dst, "<nil>")
}
return e.AppendString(dst, reflect.TypeOf(i).String())
}
// AppendObjectData takes in an object that is already in a byte array // AppendObjectData takes in an object that is already in a byte array
// and adds it to the dst. // and adds it to the dst.
func (Encoder) AppendObjectData(dst []byte, o []byte) []byte { func (Encoder) AppendObjectData(dst []byte, o []byte) []byte {

View File

@ -166,28 +166,6 @@ func Test_appendMac(t *testing.T) {
} }
} }
func Test_appendType(t *testing.T) {
typeTests := []struct {
label string
input interface{}
want []byte
}{
{"int", 42, []byte(`"int"`)},
{"MAC", net.HardwareAddr{0x12, 0x34, 0x00, 0x00, 0x90, 0xab}, []byte(`"net.HardwareAddr"`)},
{"float64", float64(2.50), []byte(`"float64"`)},
{"nil", nil, []byte(`"<nil>"`)},
{"bool", true, []byte(`"bool"`)},
}
for _, tt := range typeTests {
t.Run(tt.label, func(t *testing.T) {
if got := enc.AppendType([]byte{}, tt.input); !reflect.DeepEqual(got, tt.want) {
t.Errorf("appendType() = %s, want %s", got, tt.want)
}
})
}
}
func Test_appendObjectData(t *testing.T) { func Test_appendObjectData(t *testing.T) {
tests := []struct { tests := []struct {
dst []byte dst []byte

View File

@ -6,8 +6,8 @@
package journald package journald
// This file provides a zlog writer so that logs printed // This file provides a zerolog writer so that logs printed
// using zlog library can be sent to a journalD. // using zerolog 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"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/internal/cbor" "github.com/rs/zerolog/internal/cbor"
) )
const defaultJournalDPrio = journal.PriNotice const defaultJournalDPrio = journal.PriNotice
// NewJournalDWriter returns a zlog log destination // NewJournalDWriter returns a zerolog 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 zlog Level string into // levelToJPrio converts zerolog Level string into
// journalD's priority values. JournalD has more // journalD's priority values. JournalD has more
// priorities than zlog. // priorities than zerolog.
func levelToJPrio(zLevel string) journal.Priority { func levelToJPrio(zLevel string) journal.Priority {
lvl, _ := zlog.ParseLevel(zLevel) lvl, _ := zerolog.ParseLevel(zLevel)
switch lvl { switch lvl {
case zlog.TraceLevel: case zerolog.TraceLevel:
return journal.PriDebug return journal.PriDebug
case zlog.DebugLevel: case zerolog.DebugLevel:
return journal.PriDebug return journal.PriDebug
case zlog.InfoLevel: case zerolog.InfoLevel:
return journal.PriInfo return journal.PriInfo
case zlog.WarnLevel: case zerolog.WarnLevel:
return journal.PriWarning return journal.PriWarning
case zlog.ErrorLevel: case zerolog.ErrorLevel:
return journal.PriErr return journal.PriErr
case zlog.FatalLevel: case zerolog.FatalLevel:
return journal.PriCrit return journal.PriCrit
case zlog.PanicLevel: case zerolog.PanicLevel:
return journal.PriEmerg return journal.PriEmerg
case zlog.NoLevel: case zerolog.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[zlog.LevelFieldName].(string); ok { if l, ok := event[zerolog.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 zlog.LevelFieldName, zlog.TimestampFieldName: case zerolog.LevelFieldName, zerolog.TimestampFieldName:
continue continue
case zlog.MessageFieldName: case zerolog.MessageFieldName:
msg, _ = value.(string) msg, _ = value.(string)
continue continue
} }
@ -102,7 +102,7 @@ func (w journalWriter) Write(p []byte) (n int, err error) {
case json.Number: case json.Number:
args[jKey] = fmt.Sprint(value) args[jKey] = fmt.Sprint(value)
default: default:
b, err := zlog.InterfaceMarshalFunc(value) b, err := json.Marshal(value)
if err != nil { if err != nil {
args[jKey] = fmt.Sprintf("[error: %v]", err) args[jKey] = fmt.Sprintf("[error: %v]", err)
} else { } else {

View File

@ -7,12 +7,12 @@ import (
"io" "io"
"testing" "testing"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/journald" "github.com/rs/zerolog/journald"
) )
func ExampleNewJournalDWriter() { func ExampleNewJournalDWriter() {
log := zlog.New(journald.NewJournalDWriter()) log := zerolog.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()
) )
zlog.ErrorHandler = func(err error) { zerolog.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 := zlog.New(io.MultiWriter(w1, w2, w3)).With().Logger() log := zerolog.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!")

68
log.go
View File

@ -1,13 +1,13 @@
// Package zlog provides a lightweight logging library dedicated to JSON logging. // Package zerolog 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 "tuxpa.in/a/zlog/log" // import "github.com/rs/zerolog/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 "tuxpa.in/a/zlog/log". // NOTE: To import the global logger, import the "log" subpackage "github.com/rs/zerolog/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 := zlog.New(os.Stderr).With().Timestamp().Logger() // logger := zerolog.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
// //
// zlog.SetGlobalLevel(zlog.InfoLevel) // zerolog.SetGlobalLevel(zerolog.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(&zlog.BasicSampler{N: 10}) // sampled := log.Sample(&zerolog.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,24 +70,25 @@
// // Create the hook: // // Create the hook:
// type SeverityHook struct{} // type SeverityHook struct{}
// //
// func (h SeverityHook) Run(e *zlog.Event, level zlog.Level, msg string) { // func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
// if level != zlog.NoLevel { // if level != zerolog.NoLevel {
// e.Str("severity", level.String()) // e.Str("severity", level.String())
// } // }
// } // }
// //
// // And use it: // // And use it:
// var h SeverityHook // var h SeverityHook
// log := zlog.New(os.Stdout).Hook(h) // log := zerolog.New(os.Stdout).Hook(h)
// log.Warn().Msg("") // log.Warn().Msg("")
// // Output: {"level":"warn","severity":"warn"} // // Output: {"level":"warn","severity":"warn"}
// //
// # Caveats //
// Caveats
// //
// 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 := zlog.New(os.Stderr).With().Timestamp().Logger() // logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
// logger.Info(). // logger.Info().
// Timestamp(). // Timestamp().
// Msg("dup") // Msg("dup")
@ -95,16 +96,14 @@
// //
// 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 zlog package zerolog
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
"strconv" "strconv"
"strings"
) )
// Level defines log levels. // Level defines log levels.
@ -157,27 +156,27 @@ func (l Level) String() string {
return strconv.Itoa(int(l)) return strconv.Itoa(int(l))
} }
// ParseLevel converts a level string into a zlog Level value. // ParseLevel converts a level string into a zerolog 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 { switch levelStr {
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(TraceLevel)): case LevelFieldMarshalFunc(TraceLevel):
return TraceLevel, nil return TraceLevel, nil
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(DebugLevel)): case LevelFieldMarshalFunc(DebugLevel):
return DebugLevel, nil return DebugLevel, nil
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(InfoLevel)): case LevelFieldMarshalFunc(InfoLevel):
return InfoLevel, nil return InfoLevel, nil
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(WarnLevel)): case LevelFieldMarshalFunc(WarnLevel):
return WarnLevel, nil return WarnLevel, nil
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(ErrorLevel)): case LevelFieldMarshalFunc(ErrorLevel):
return ErrorLevel, nil return ErrorLevel, nil
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(FatalLevel)): case LevelFieldMarshalFunc(FatalLevel):
return FatalLevel, nil return FatalLevel, nil
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(PanicLevel)): case LevelFieldMarshalFunc(PanicLevel):
return PanicLevel, nil return PanicLevel, nil
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(Disabled)): case LevelFieldMarshalFunc(Disabled):
return Disabled, nil return Disabled, nil
case strings.EqualFold(levelStr, LevelFieldMarshalFunc(NoLevel)): case LevelFieldMarshalFunc(NoLevel):
return NoLevel, nil return NoLevel, nil
} }
i, err := strconv.Atoi(levelStr) i, err := strconv.Atoi(levelStr)
@ -190,21 +189,6 @@ func ParseLevel(levelStr string) (Level, error) {
return Level(i), nil return Level(i), nil
} }
// UnmarshalText implements encoding.TextUnmarshaler to allow for easy reading from toml/yaml/json formats
func (l *Level) UnmarshalText(text []byte) error {
if l == nil {
return errors.New("can't unmarshal a nil *Level")
}
var err error
*l, err = ParseLevel(string(text))
return err
}
// MarshalText implements encoding.TextMarshaler to allow for easy writing into toml/yaml/json formats
func (l Level) MarshalText() ([]byte, error) {
return []byte(LevelFieldMarshalFunc(l)), nil
}
// A Logger represents an active logging object that generates lines // A Logger represents an active logging object that generates lines
// of JSON output to an io.Writer. Each logging operation makes a single // of JSON output to an io.Writer. Each logging operation makes a single
// call to the Writer's Write method. There is no guarantee on access // call to the Writer's Write method. There is no guarantee on access
@ -308,9 +292,7 @@ func (l Logger) Sample(s Sampler) Logger {
// Hook returns a logger with the h Hook. // Hook returns a logger with the h Hook.
func (l Logger) Hook(h Hook) Logger { func (l Logger) Hook(h Hook) Logger {
newHooks := make([]Hook, len(l.hooks), len(l.hooks)+1) l.hooks = append(l.hooks, h)
copy(newHooks, l.hooks)
l.hooks = append(newHooks, h)
return l return l
} }

View File

@ -1,4 +1,4 @@
// Package log provides a global logger for zlog. // Package log provides a global logger for zerolog.
package log package log
import ( import (
@ -6,42 +6,35 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"time"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog"
) )
// Logger is the global logger. // Logger is the global logger.
var Logger = zlog.New(nil).Output( var Logger = zerolog.New(os.Stderr).With().Timestamp().Logger()
zerolog.ConsoleWriter{
Out: os.Stderr,
TimeFormat: time.RFC3339,
},
).With().Timestamp().Logger()
// 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) zlog.Logger { func Output(w io.Writer) zerolog.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() zlog.Context { func With() zerolog.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 zlog.Level) zlog.Logger { func Level(level zerolog.Level) zerolog.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 zlog.Sampler) zlog.Logger { func Sample(s zerolog.Sampler) zerolog.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 zlog.Hook) zlog.Logger { func Hook(h zerolog.Hook) zerolog.Logger {
return Logger.Hook(h) return Logger.Hook(h)
} }
@ -49,99 +42,73 @@ func Hook(h zlog.Hook) zlog.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) *zlog.Event { func Err(err error) *zerolog.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() *zlog.Event { func Trace() *zerolog.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() *zlog.Event { func Debug() *zerolog.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() *zlog.Event { func Info() *zerolog.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() *zlog.Event { func Warn() *zerolog.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() *zlog.Event { func Error() *zerolog.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() *zlog.Event { func Fatal() *zerolog.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() *zlog.Event { func Panic() *zerolog.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 zlog.Level) *zlog.Event { func WithLevel(level zerolog.Level) *zerolog.Event {
return Logger.WithLevel(level) return Logger.WithLevel(level)
} }
// Log starts a new message with no level. Setting zlog.GlobalLevel to // Log starts a new message with no level. Setting zerolog.GlobalLevel to
// zlog.Disabled will still disable events produced by this method. // zerolog.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() *zlog.Event { func Log() *zerolog.Event {
return Logger.Log() return Logger.Log()
} }
@ -157,12 +124,8 @@ 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) *zlog.Logger { func Ctx(ctx context.Context) *zerolog.Logger {
return zlog.Ctx(ctx) return zerolog.Ctx(ctx)
} }

View File

@ -1,4 +1,3 @@
//go:build !binary_log
// +build !binary_log // +build !binary_log
package log_test package log_test
@ -9,8 +8,8 @@ import (
"os" "os"
"time" "time"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
"tuxpa.in/a/zlog/log" "github.com/rs/zerolog/log"
) )
// setup would normally be an init() function, however, there seems // setup would normally be an init() function, however, there seems
@ -18,16 +17,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 zlog.TimeFieldFormat to an empty string, // If you set zerolog.TimeFieldFormat to an empty string,
// logs will write with UNIX time // logs will write with UNIX time
zlog.TimeFieldFormat = "" zerolog.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 zlog.TimestampFunc // examples to pass, we need to override zerolog.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
zlog.TimestampFunc = func() time.Time { zerolog.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 = zlog.New(os.Stdout).With().Timestamp().Logger() log.Logger = zerolog.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
@ -131,9 +130,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
zlog.SetGlobalLevel(zlog.InfoLevel) zerolog.SetGlobalLevel(zerolog.InfoLevel)
if *debug { if *debug {
zlog.SetGlobalLevel(zlog.DebugLevel) zerolog.SetGlobalLevel(zerolog.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 zlog_test package zerolog_test
import ( import (
"errors" "errors"
@ -10,18 +10,18 @@ import (
"os" "os"
"time" "time"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
) )
func ExampleNew() { func ExampleNew() {
log := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout). log := zerolog.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 := zlog.New(os.Stdout).Level(zlog.WarnLevel) log := zerolog.New(os.Stdout).Level(zerolog.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 := zlog.New(os.Stdout).Sample(&zlog.BasicSampler{N: 2}) log := zerolog.New(os.Stdout).Sample(&zerolog.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 *zlog.Event, l zlog.Level, msg string) { func (h LevelNameHook) Run(e *zerolog.Event, l zerolog.Level, msg string) {
if l != zlog.NoLevel { if l != zerolog.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 *zlog.Event, l zlog.Level, msg string) {
type MessageHook string type MessageHook string
func (h MessageHook) Run(e *zlog.Event, l zlog.Level, msg string) { func (h MessageHook) Run(e *zerolog.Event, l zerolog.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 := zlog.New(os.Stdout).Hook(levelNameHook).Hook(messageHook) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.New(os.Stdout)
log.WithLevel(zlog.InfoLevel). log.WithLevel(zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
Dict("dict", zlog.Dict(). Dict("dict", zerolog.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 *zlog.Event) { func (u User) MarshalZerologObject(e *zerolog.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 *zlog.Event) { func (p Price) MarshalZerologObject(e *zerolog.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 *zlog.Event) {
type Users []User type Users []User
func (uu Users) MarshalZerologArray(a *zlog.Array) { func (uu Users) MarshalZerologArray(a *zerolog.Array) {
for _, u := range uu { for _, u := range uu {
a.Object(u) a.Object(u)
} }
} }
func ExampleEvent_Array() { func ExampleEvent_Array() {
log := zlog.New(os.Stdout) log := zerolog.New(os.Stdout)
log.Log(). log.Log().
Str("foo", "bar"). Str("foo", "bar").
Array("array", zlog.Arr(). Array("array", zerolog.Arr().
Str("baz"). Str("baz").
Int(1). Int(1).
Dict(zlog.Dict(). Dict(zerolog.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 := zlog.New(os.Stdout) log := zerolog.New(os.Stdout)
// Users implements zlog.LogArrayMarshaler // Users implements zerolog.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 := zlog.New(os.Stdout) log := zerolog.New(os.Stdout)
// User implements zlog.LogObjectMarshaler // User implements zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout) log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Dict("dict", zlog.Dict(). Dict("dict", zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Array("array", zlog.Arr(). Array("array", zerolog.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 zlog.LogArrayMarshaler // Users implements zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 zlog.LogObjectMarshaler // User implements zerolog.LogObjectMarshaler
u := User{"John", 35, time.Time{}} u := User{"John", 35, time.Time{}}
log := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.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 := zlog.New(os.Stdout).With(). log := zerolog.New(os.Stdout).With().
Str("foo", "bar"). Str("foo", "bar").
Fields(fields). Fields(fields).
Logger() Logger()

View File

@ -1,4 +1,4 @@
package zlog package zerolog
import ( import (
"bytes" "bytes"
@ -320,7 +320,6 @@ func TestFields(t *testing.T) {
Bytes("bytes", []byte("bar")). Bytes("bytes", []byte("bar")).
Hex("hex", []byte{0x12, 0xef}). Hex("hex", []byte{0x12, 0xef}).
RawJSON("json", []byte(`{"some":"json"}`)). RawJSON("json", []byte(`{"some":"json"}`)).
RawCBOR("cbor", []byte{0x83, 0x01, 0x82, 0x02, 0x03, 0x82, 0x04, 0x05}).
Func(func(e *Event) { e.Str("func", "func_output") }). Func(func(e *Event) { e.Str("func", "func_output") }).
AnErr("some_err", nil). AnErr("some_err", nil).
Err(errors.New("some error")). Err(errors.New("some error")).
@ -345,7 +344,7 @@ func TestFields(t *testing.T) {
Time("time", time.Time{}). Time("time", time.Time{}).
TimeDiff("diff", now, now.Add(-10*time.Second)). TimeDiff("diff", now, now.Add(-10*time.Second)).
Msg("") Msg("")
if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","string":"foo","stringer":"127.0.0.1","stringer_nil":null,"bytes":"bar","hex":"12ef","json":{"some":"json"},"cbor":"data:application/cbor;base64,gwGCAgOCBAU=","func":"func_output","error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"IPv4":"192.168.0.100","IPv6":"2001:db8:85a3::8a2e:370:7334","Mac":"00:14:22:01:23:45","Prefix":"192.168.0.100/24","float32":11.1234,"float64":12.321321321,"dur":1000,"time":"0001-01-01T00:00:00Z","diff":10000}`+"\n"; got != want { if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","string":"foo","stringer":"127.0.0.1","stringer_nil":null,"bytes":"bar","hex":"12ef","json":{"some":"json"},"func":"func_output","error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"IPv4":"192.168.0.100","IPv6":"2001:db8:85a3::8a2e:370:7334","Mac":"00:14:22:01:23:45","Prefix":"192.168.0.100/24","float32":11.1234,"float64":12.321321321,"dur":1000,"time":"0001-01-01T00:00:00Z","diff":10000}`+"\n"; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want) t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
} }
} }
@ -783,7 +782,7 @@ func TestCallerMarshalFunc(t *testing.T) {
// test default behaviour this is really brittle due to the line numbers // test default behaviour this is really brittle due to the line numbers
// actually mattering for validation // actually mattering for validation
pc, file, line, _ := runtime.Caller(0) _, file, line, _ := runtime.Caller(0)
caller := fmt.Sprintf("%s:%d", file, line+2) caller := fmt.Sprintf("%s:%d", file, line+2)
log.Log().Caller().Msg("msg") log.Log().Caller().Msg("msg")
if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","message":"msg"}`+"\n"; got != want { if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","message":"msg"}`+"\n"; got != want {
@ -794,16 +793,16 @@ func TestCallerMarshalFunc(t *testing.T) {
// test custom behavior. In this case we'll take just the last directory // test custom behavior. In this case we'll take just the last directory
origCallerMarshalFunc := CallerMarshalFunc origCallerMarshalFunc := CallerMarshalFunc
defer func() { CallerMarshalFunc = origCallerMarshalFunc }() defer func() { CallerMarshalFunc = origCallerMarshalFunc }()
CallerMarshalFunc = func(pc uintptr, file string, line int) string { CallerMarshalFunc = func(file string, line int) string {
parts := strings.Split(file, "/") parts := strings.Split(file, "/")
if len(parts) > 1 { if len(parts) > 1 {
return strings.Join(parts[len(parts)-2:], "/") + ":" + strconv.Itoa(line) return strings.Join(parts[len(parts)-2:], "/") + ":" + strconv.Itoa(line)
} }
return runtime.FuncForPC(pc).Name() + ":" + file + ":" + strconv.Itoa(line) return file + ":" + strconv.Itoa(line)
} }
pc, file, line, _ = runtime.Caller(0) _, file, line, _ = runtime.Caller(0)
caller = CallerMarshalFunc(pc, file, line+2) caller = CallerMarshalFunc(file, line+2)
log.Log().Caller().Msg("msg") log.Log().Caller().Msg("msg")
if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","message":"msg"}`+"\n"; got != want { if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","message":"msg"}`+"\n"; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want) t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
@ -908,33 +907,6 @@ func TestLevel_String(t *testing.T) {
} }
} }
func TestLevel_MarshalText(t *testing.T) {
tests := []struct {
name string
l Level
want string
}{
{"trace", TraceLevel, "trace"},
{"debug", DebugLevel, "debug"},
{"info", InfoLevel, "info"},
{"warn", WarnLevel, "warn"},
{"error", ErrorLevel, "error"},
{"fatal", FatalLevel, "fatal"},
{"panic", PanicLevel, "panic"},
{"disabled", Disabled, "disabled"},
{"nolevel", NoLevel, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got, err := tt.l.MarshalText(); err != nil {
t.Errorf("MarshalText couldn't marshal: %v", tt.l)
} else if string(got) != tt.want {
t.Errorf("String() = %v, want %v", string(got), tt.want)
}
})
}
}
func TestParseLevel(t *testing.T) { func TestParseLevel(t *testing.T) {
type args struct { type args struct {
levelStr string levelStr string
@ -971,41 +943,3 @@ func TestParseLevel(t *testing.T) {
}) })
} }
} }
func TestUnmarshalTextLevel(t *testing.T) {
type args struct {
levelStr string
}
tests := []struct {
name string
args args
want Level
wantErr bool
}{
{"trace", args{"trace"}, TraceLevel, false},
{"debug", args{"debug"}, DebugLevel, false},
{"info", args{"info"}, InfoLevel, false},
{"warn", args{"warn"}, WarnLevel, false},
{"error", args{"error"}, ErrorLevel, false},
{"fatal", args{"fatal"}, FatalLevel, false},
{"panic", args{"panic"}, PanicLevel, false},
{"disabled", args{"disabled"}, Disabled, false},
{"nolevel", args{""}, NoLevel, false},
{"-1", args{"-1"}, TraceLevel, false},
{"-2", args{"-2"}, Level(-2), false},
{"-3", args{"-3"}, Level(-3), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var l Level
err := l.UnmarshalText([]byte(tt.args.levelStr))
if (err != nil) != tt.wantErr {
t.Errorf("UnmarshalText() error = %v, wantErr %v", err, tt.wantErr)
return
}
if l != tt.want {
t.Errorf("UnmarshalText() got = %v, want %v", l, tt.want)
}
})
}
}

View File

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

View File

@ -42,32 +42,15 @@ func frameField(f errors.Frame, s *state, c rune) string {
// MarshalStack implements pkg/errors stack trace marshaling. // MarshalStack implements pkg/errors stack trace marshaling.
// //
// zlog.ErrorStackMarshaler = MarshalStack // zerolog.ErrorStackMarshaler = MarshalStack
func MarshalStack(err error) interface{} { func MarshalStack(err error) interface{} {
type stackTracer interface { type stackTracer interface {
StackTrace() errors.StackTrace StackTrace() errors.StackTrace
} }
var sterr stackTracer sterr, ok := err.(stackTracer)
var ok bool
for err != nil {
sterr, ok = err.(stackTracer)
if ok {
break
}
u, ok := err.(interface {
Unwrap() error
})
if !ok { if !ok {
return nil return nil
} }
err = u.Unwrap()
}
if sterr == nil {
return nil
}
st := sterr.StackTrace() st := sterr.StackTrace()
s := &state{} s := &state{}
out := make([]map[string]string, 0, len(st)) out := make([]map[string]string, 0, len(st))

View File

@ -4,50 +4,49 @@ package pkgerrors
import ( import (
"bytes" "bytes"
"fmt"
"regexp" "regexp"
"testing" "testing"
"github.com/pkg/errors" "github.com/pkg/errors"
"tuxpa.in/a/zlog" "github.com/rs/zerolog"
) )
func TestLogStack(t *testing.T) { func TestLogStack(t *testing.T) {
zlog.ErrorStackMarshaler = MarshalStack zerolog.ErrorStackMarshaler = MarshalStack
out := &bytes.Buffer{} out := &bytes.Buffer{}
log := zlog.New(out) log := zerolog.New(out)
err := fmt.Errorf("from error: %w", errors.New("error message")) err := errors.Wrap(errors.New("error message"), "from error")
log.Log().Stack().Err(err).Msg("") log.Log().Stack().Err(err).Msg("")
got := out.String() got := out.String()
want := `\{"stack":\[\{"func":"TestLogStack","line":"21","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n` want := `\{"stack":\[\{"func":"TestLogStack","line":"20","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
if ok, _ := regexp.MatchString(want, got); !ok { if ok, _ := regexp.MatchString(want, got); !ok {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want) t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
} }
} }
func TestLogStackFromContext(t *testing.T) { func TestLogStackFromContext(t *testing.T) {
zlog.ErrorStackMarshaler = MarshalStack zerolog.ErrorStackMarshaler = MarshalStack
out := &bytes.Buffer{} out := &bytes.Buffer{}
log := zlog.New(out).With().Stack().Logger() // calling Stack() on log context instead of event log := zerolog.New(out).With().Stack().Logger() // calling Stack() on log context instead of event
err := fmt.Errorf("from error: %w", errors.New("error message")) 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()
got := out.String() got := out.String()
want := `\{"stack":\[\{"func":"TestLogStackFromContext","line":"37","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n` want := `\{"stack":\[\{"func":"TestLogStackFromContext","line":"36","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
if ok, _ := regexp.MatchString(want, got); !ok { if ok, _ := regexp.MatchString(want, got); !ok {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want) t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
} }
} }
func BenchmarkLogStack(b *testing.B) { func BenchmarkLogStack(b *testing.B) {
zlog.ErrorStackMarshaler = MarshalStack zerolog.ErrorStackMarshaler = MarshalStack
out := &bytes.Buffer{} out := &bytes.Buffer{}
log := zlog.New(out) log := zerolog.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 zlog package zerolog
import ( import (
"math/rand" "math/rand"

View File

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

View File

@ -1,7 +1,7 @@
// +build !windows // +build !windows
// +build !binary_log // +build !binary_log
package zlog package zerolog
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 zlog level. // method matching the zerolog 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 zlog package zerolog
import ( import (
"bytes" "bytes"

View File

@ -1,4 +1,4 @@
package zlog package zerolog
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 zlog package zerolog
import ( import (
"bytes" "bytes"