zlog/README.md

724 lines
22 KiB
Markdown
Raw Normal View History

2022-03-20 19:31:02 +00:00
###zlog
opinionated defaults on zerolog
2017-05-12 05:24:39 +00:00
# Zero Allocation JSON Logger
2022-03-20 19:19:42 +00:00
[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/git.tuxpa.in/a/zlog) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/zlog/master/LICENSE) [![Build Status](https://travis-ci.org/rs/zlog.svg?branch=master)](https://travis-ci.org/rs/zlog) [![Coverage](http://gocover.io/_badge/git.tuxpa.in/a/zlog)](http://gocover.io/git.tuxpa.in/a/zlog)
2017-05-12 05:24:39 +00:00
2022-03-20 19:19:42 +00:00
The zlog package provides a fast and simple logger dedicated to JSON output.
2017-05-20 09:03:07 +00:00
2022-03-20 19:19:42 +00:00
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.
2017-05-20 09:03:07 +00:00
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.
2017-05-20 09:03:07 +00:00
2022-03-20 19:19:42 +00:00
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).
2017-05-12 05:24:39 +00:00
2018-04-19 03:29:59 +00:00
![Pretty Logging Image](pretty.png)
2022-03-20 19:19:42 +00:00
## Who uses zlog
2018-03-26 05:34:03 +00:00
2022-03-20 19:19:42 +00:00
Find out [who uses zlog](https://git.tuxpa.in/a/zlog/wiki/Who-uses-zlog) and add your company / project to the list.
2018-03-26 05:34:03 +00:00
2017-05-12 05:24:39 +00:00
## Features
* [Blazing fast](#benchmarks)
* [Low to zero allocation](#benchmarks)
* [Leveled logging](#leveled-logging)
* [Sampling](#log-sampling)
* [Hooks](#hooks)
* [Contextual fields](#contextual-logging)
* `context.Context` integration
* [Integration with `net/http`](#integration-with-nethttp)
* [JSON and CBOR encoding formats](#binary-encoding)
* [Pretty logging for development](#pretty-logging)
* [Error Logging (with optional Stacktrace)](#error-logging)
2017-05-12 05:24:39 +00:00
## Installation
2020-01-01 20:32:59 +00:00
```bash
2022-03-20 19:19:42 +00:00
go get -u git.tuxpa.in/a/zlog/log
2017-05-12 05:24:39 +00:00
```
2018-04-19 03:29:59 +00:00
## Getting Started
### Simple Logging Example
2022-03-20 19:19:42 +00:00
For simple logging, import the global logger package **git.tuxpa.in/a/zlog/log**
2018-04-19 03:29:59 +00:00
```go
package main
2017-05-12 05:24:39 +00:00
import (
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
2017-05-12 05:24:39 +00:00
func main() {
2018-04-19 03:29:59 +00:00
// UNIX Time is faster and smaller than most timestamps
2022-03-20 19:19:42 +00:00
zlog.TimeFieldFormat = zlog.TimeFormatUnix
2018-04-19 03:29:59 +00:00
log.Print("hello world")
}
2017-09-02 02:56:35 +00:00
// Output: {"time":1516134303,"level":"debug","message":"hello world"}
2017-09-02 02:56:35 +00:00
```
> Note: By default log writes to `os.Stderr`
> Note: The default log level for `log.Print` is *debug*
2018-04-19 03:29:59 +00:00
### Contextual Logging
2022-03-20 19:19:42 +00:00
**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:
2018-04-19 03:29:59 +00:00
```go
package main
import (
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
2018-04-19 03:29:59 +00:00
)
func main() {
2022-03-20 19:19:42 +00:00
zlog.TimeFieldFormat = zlog.TimeFormatUnix
2018-04-19 03:29:59 +00:00
log.Debug().
Str("Scale", "833 cents").
Float64("Interval", 833.09).
Msg("Fibonacci is everywhere")
2022-03-20 19:31:02 +00:00
log.Debug().
Str("Name", "Tom").
Send()
2018-04-19 03:29:59 +00:00
}
// Output: {"level":"debug","Scale":"833 cents","Interval":833.09,"time":1562212768,"message":"Fibonacci is everywhere"}
// Output: {"level":"debug","Name":"Tom","time":1562212768}
2018-04-19 03:29:59 +00:00
```
> You'll note in the above example that when adding contextual fields, the fields are strongly typed. You can find the full list of supported fields [here](#standard-types)
### Leveled Logging
2017-09-02 02:56:35 +00:00
#### Simple Leveled Logging Example
2017-09-02 02:56:35 +00:00
2017-05-12 05:24:39 +00:00
```go
package main
import (
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
2022-03-20 19:19:42 +00:00
zlog.TimeFieldFormat = zlog.TimeFormatUnix
2018-04-19 03:29:59 +00:00
log.Info().Msg("hello world")
}
2017-05-12 05:24:39 +00:00
// Output: {"time":1516134303,"level":"info","message":"hello world"}
2017-05-12 05:24:39 +00:00
```
2022-03-20 19:19:42 +00:00
> 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.
2018-04-19 03:29:59 +00:00
2022-03-20 19:19:42 +00:00
**zlog** allows for logging at the following levels (from highest to lowest):
2018-04-19 03:29:59 +00:00
2022-03-20 19:19:42 +00:00
* panic (`zlog.PanicLevel`, 5)
* fatal (`zlog.FatalLevel`, 4)
* error (`zlog.ErrorLevel`, 3)
* warn (`zlog.WarnLevel`, 2)
* info (`zlog.InfoLevel`, 1)
* debug (`zlog.DebugLevel`, 0)
* trace (`zlog.TraceLevel`, -1)
2022-03-20 19:19:42 +00:00
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.
2017-05-12 05:24:39 +00:00
#### Setting Global Log Level
This example uses command-line flags to demonstrate various outputs depending on the chosen log level.
2017-05-12 05:24:39 +00:00
```go
package main
import (
2018-04-19 03:29:59 +00:00
"flag"
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
2022-03-20 19:19:42 +00:00
zlog.TimeFieldFormat = zlog.TimeFormatUnix
2018-04-19 03:29:59 +00:00
debug := flag.Bool("debug", false, "sets log level to debug")
2018-04-19 03:29:59 +00:00
flag.Parse()
2018-04-19 03:29:59 +00:00
// Default level for this example is info, unless debug flag is present
2022-03-20 19:19:42 +00:00
zlog.SetGlobalLevel(zlog.InfoLevel)
2018-04-19 03:29:59 +00:00
if *debug {
2022-03-20 19:19:42 +00:00
zlog.SetGlobalLevel(zlog.DebugLevel)
2018-04-19 03:29:59 +00:00
}
2018-04-19 03:29:59 +00:00
log.Debug().Msg("This message appears only when log level set to Debug")
log.Info().Msg("This message appears when log level set to Debug or Info")
2018-04-19 03:29:59 +00:00
if e := log.Debug(); e.Enabled() {
// Compute log output only if enabled.
value := "bar"
e.Str("foo", value).Msg("some debug message")
}
}
```
2018-04-19 03:29:59 +00:00
Info Output (no flag)
2018-04-19 03:29:59 +00:00
```bash
$ ./logLevelExample
{"time":1516387492,"level":"info","message":"This message appears when log level set to Debug or Info"}
```
2017-05-12 05:24:39 +00:00
Debug Output (debug flag set)
2018-04-19 03:29:59 +00:00
```bash
$ ./logLevelExample -debug
{"time":1516387573,"level":"debug","message":"This message appears only when log level set to Debug"}
{"time":1516387573,"level":"info","message":"This message appears when log level set to Debug or Info"}
{"time":1516387573,"level":"debug","foo":"bar","message":"some debug message"}
2017-05-12 05:24:39 +00:00
```
2018-04-19 03:29:59 +00:00
#### Logging without Level or Message
You may choose to log without a specific level by using the `Log` method. You may also write without a message by setting an empty string in the `msg string` parameter of the `Msg` method. Both are demonstrated in the example below.
```go
package main
import (
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
2018-04-19 03:29:59 +00:00
)
func main() {
2022-03-20 19:19:42 +00:00
zlog.TimeFieldFormat = zlog.TimeFormatUnix
2018-04-19 03:29:59 +00:00
log.Log().
Str("foo", "bar").
Msg("")
}
// Output: {"time":1494567715,"foo":"bar"}
```
### Error Logging
You can log errors using the `Err` method
```go
package main
import (
"errors"
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
2022-03-20 19:19:42 +00:00
zlog.TimeFieldFormat = zlog.TimeFormatUnix
err := errors.New("seems we have an error here")
log.Error().Err(err).Msg("")
}
// Output: {"level":"error","error":"seems we have an error here","time":1609085256}
```
2022-03-20 19:19:42 +00:00
> The default field name for errors is `error`, you can change this by setting `zlog.ErrorFieldName` to meet your needs.
#### Error Logging with Stacktrace
2022-03-20 19:31:02 +00:00
Using `github.com/pkg/errors`, you can add a formatted stacktrace to your errors.
```go
package main
import (
"github.com/pkg/errors"
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog/pkgerrors"
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
2022-03-20 19:19:42 +00:00
zlog.TimeFieldFormat = zlog.TimeFormatUnix
zlog.ErrorStackMarshaler = pkgerrors.MarshalStack
err := outer()
log.Error().Stack().Err(err).Msg("")
}
func inner() error {
return errors.New("seems we have an error here")
}
func middle() error {
err := inner()
if err != nil {
return err
}
return nil
}
func outer() error {
err := middle()
if err != nil {
return err
}
return nil
}
// 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}
```
2022-03-20 19:19:42 +00:00
> zlog.ErrorStackMarshaler must be set in order for the stack to output anything.
#### Logging Fatal Messages
```go
package main
import (
2018-04-19 03:29:59 +00:00
"errors"
2022-03-20 19:19:42 +00:00
"git.tuxpa.in/a/zlog"
"git.tuxpa.in/a/zlog/log"
)
func main() {
2018-04-19 03:29:59 +00:00
err := errors.New("A repo man spends his life getting into tense situations")
service := "myservice"
2022-03-20 19:19:42 +00:00
zlog.TimeFieldFormat = zlog.TimeFormatUnix
2018-04-19 03:29:59 +00:00
log.Fatal().
Err(err).
Str("service", service).
Msgf("Cannot start %s", service)
}
2017-05-12 05:24:39 +00:00
// Output: {"time":1516133263,"level":"fatal","error":"A repo man spends his life getting into tense situations","service":"myservice","message":"Cannot start myservice"}
// exit status 1
```
2018-04-19 03:29:59 +00:00
> NOTE: Using `Msgf` generates one allocation even when the logger is disabled.
2017-05-12 05:24:39 +00:00
2017-05-12 05:24:39 +00:00
### Create logger instance to manage different outputs
```go
2022-03-20 19:19:42 +00:00
logger := zlog.New(os.Stderr).With().Timestamp().Logger()
2017-05-12 05:24:39 +00:00
logger.Info().Str("foo", "bar").Msg("hello world")
// Output: {"level":"info","time":1494567715,"message":"hello world","foo":"bar"}
```
### Sub-loggers let you chain loggers with additional context
```go
sublogger := log.With().
2018-05-31 17:33:44 +00:00
Str("component", "foo").
2017-05-12 05:24:39 +00:00
Logger()
sublogger.Info().Msg("hello world")
// Output: {"level":"info","time":1494567715,"message":"hello world","component":"foo"}
```
### Pretty logging
2022-03-20 19:19:42 +00:00
To log a human-friendly, colorized output, use `zlog.ConsoleWriter`:
```go
2022-03-20 19:19:42 +00:00
log.Logger = log.Output(zlog.ConsoleWriter{Out: os.Stderr})
log.Info().Str("foo", "bar").Msg("Hello world")
// Output: 3:04PM INF Hello World foo=bar
```
To customize the configuration and formatting:
```go
2022-03-20 19:19:42 +00:00
output := zlog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
output.FormatLevel = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("| %-6s|", i))
}
output.FormatMessage = func(i interface{}) string {
return fmt.Sprintf("***%s****", i)
}
output.FormatFieldName = func(i interface{}) string {
return fmt.Sprintf("%s:", i)
}
output.FormatFieldValue = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("%s", i))
}
2022-03-20 19:19:42 +00:00
log := zlog.New(output).With().Timestamp().Logger()
log.Info().Str("foo", "bar").Msg("Hello World")
// Output: 2006-01-02T15:04:05Z07:00 | INFO | ***Hello World**** foo:BAR
```
2017-05-18 07:10:45 +00:00
### Sub dictionary
```go
log.Info().
Str("foo", "bar").
2022-03-20 19:19:42 +00:00
Dict("dict", zlog.Dict().
2017-05-18 07:10:45 +00:00
Str("bar", "baz").
2018-05-13 05:12:35 +00:00
Int("n", 1),
2017-05-18 07:10:45 +00:00
).Msg("hello world")
// Output: {"level":"info","time":1494567715,"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}
```
2017-05-12 05:24:39 +00:00
### Customize automatic field names
```go
2022-03-20 19:19:42 +00:00
zlog.TimestampFieldName = "t"
zlog.LevelFieldName = "l"
zlog.MessageFieldName = "m"
2017-05-12 05:24:39 +00:00
log.Info().Msg("hello world")
// Output: {"l":"info","t":1494567715,"m":"hello world"}
```
### Add contextual fields to the global logger
```go
log.Logger = log.With().Str("foo", "bar").Logger()
```
### Add file and line number to log
Equivalent of `Llongfile`:
```go
log.Logger = log.With().Caller().Logger()
log.Info().Msg("hello world")
// Output: {"level": "info", "message": "hello world", "caller": "/go/src/your_project/some_file:21"}
```
Equivalent of `Lshortfile`:
```go
2022-03-20 19:19:42 +00:00
zlog.CallerMarshalFunc = func(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
If your writer might be slow or not thread-safe and you need your log producers to never get slowed down by a slow writer, you can use a `diode.Writer` as follows:
```go
wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) {
fmt.Printf("Logger Dropped %d messages", missed)
})
2022-03-20 19:19:42 +00:00
log := zlog.New(wr)
log.Print("test")
```
You will need to install `code.cloudfoundry.org/go-diodes` to use this feature.
2017-05-12 05:24:39 +00:00
### Log Sampling
```go
2022-03-20 19:19:42 +00:00
sampled := log.Sample(&zlog.BasicSampler{N: 10})
2017-05-12 05:24:39 +00:00
sampled.Info().Msg("will be logged every 10 messages")
2017-08-29 01:52:15 +00:00
// Output: {"time":1494567715,"level":"info","message":"will be logged every 10 messages"}
2017-05-12 05:24:39 +00:00
```
2017-08-29 01:52:15 +00:00
More advanced sampling:
```go
// Will let 5 debug messages per period of 1 second.
// Over 5 debug message, 1 every 100 debug messages are logged.
// Other levels are not sampled.
2022-03-20 19:19:42 +00:00
sampled := log.Sample(zlog.LevelSampler{
DebugSampler: &zlog.BurstSampler{
2017-08-29 01:52:15 +00:00
Burst: 5,
Period: 1*time.Second,
2022-03-20 19:19:42 +00:00
NextSampler: &zlog.BasicSampler{N: 100},
2017-08-29 01:52:15 +00:00
},
})
sampled.Debug().Msg("hello world")
// Output: {"time":1494567715,"level":"debug","message":"hello world"}
```
2017-12-01 17:52:37 +00:00
### Hooks
```go
type SeverityHook struct{}
2022-03-20 19:19:42 +00:00
func (h SeverityHook) Run(e *zlog.Event, level zlog.Level, msg string) {
if level != zlog.NoLevel {
2017-12-01 17:52:37 +00:00
e.Str("severity", level.String())
}
}
hooked := log.Hook(SeverityHook{})
hooked.Warn().Msg("")
// Output: {"level":"warn","severity":"warn"}
```
2017-08-29 01:52:15 +00:00
2017-05-20 07:22:37 +00:00
### Pass a sub-logger by context
```go
ctx := log.With().Str("component", "module").Logger().WithContext(ctx)
2017-05-20 07:22:37 +00:00
log.Ctx(ctx).Info().Msg("hello world")
// Output: {"component":"module","level":"info","message":"hello world"}
```
### Set as standard logger output
```go
2022-03-20 19:19:42 +00:00
log := zlog.New(os.Stdout).With().
Str("foo", "bar").
Logger()
stdlog.SetFlags(0)
stdlog.SetOutput(log)
stdlog.Print("hello world")
// Output: {"foo":"bar","message":"hello world"}
```
### Integration with `net/http`
2022-03-20 19:19:42 +00:00
The `git.tuxpa.in/a/zlog/hlog` package provides some helpers to integrate zlog with `http.Handler`.
In this example we use [alice](https://github.com/justinas/alice) to install logger for better readability.
```go
2022-03-20 19:19:42 +00:00
log := zlog.New(os.Stdout).With().
2017-05-20 09:22:57 +00:00
Timestamp().
Str("role", "my-service").
Str("host", host).
Logger()
c := alice.New()
// Install the logger handler with default output on the console
c = c.Append(hlog.NewHandler(log))
// Install some provided extra handler to set some request's context fields.
2020-05-14 15:27:19 +00:00
// Thanks to that handler, all our logs will come with some prepopulated fields.
2017-07-10 10:35:34 +00:00
c = c.Append(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
hlog.FromRequest(r).Info().
Str("method", r.Method).
2020-05-28 17:43:18 +00:00
Stringer("url", r.URL).
2017-07-10 10:35:34 +00:00
Int("status", status).
Int("size", size).
Dur("duration", duration).
Msg("")
}))
c = c.Append(hlog.RemoteAddrHandler("ip"))
c = c.Append(hlog.UserAgentHandler("user_agent"))
c = c.Append(hlog.RefererHandler("referer"))
c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id"))
// Here is your final handler
h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the logger from the request's context. You can safely assume it
// will be always there: if the handler is removed, hlog.FromRequest
// will return a no-op logger.
hlog.FromRequest(r).Info().
Str("user", "current user").
Str("status", "ok").
Msg("Something happened")
2017-05-20 09:22:57 +00:00
// Output: {"level":"info","time":"2001-02-03T04:05:06Z","role":"my-service","host":"local-hostname","req_id":"b4g0l5t6tfid6dtrapu0","user":"current user","status":"ok","message":"Something happened"}
}))
http.Handle("/", h)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal().Err(err).Msg("Startup failed")
}
```
## Multiple Log Output
2022-03-20 19:31:02 +00:00
`zlog.MultiLevelWriter` may be used to send the log message to multiple outputs.
In this example, we send the log message to both `os.Stdout` and the in-built ConsoleWriter.
```go
func main() {
2022-03-20 19:19:42 +00:00
consoleWriter := zlog.ConsoleWriter{Out: os.Stdout}
2022-03-20 19:19:42 +00:00
multi := zlog.MultiLevelWriter(consoleWriter, os.Stdout)
2022-03-20 19:19:42 +00:00
logger := zlog.New(multi).With().Timestamp().Logger()
logger.Info().Msg("Hello World!")
}
// Output (Line 1: Console; Line 2: Stdout)
// 12:36PM INF Hello World!
// {"level":"info","time":"2019-11-07T12:36:38+03:00","message":"Hello World!"}
```
2017-05-12 05:24:39 +00:00
## Global Settings
Some settings can be changed and will be applied to all loggers:
2017-05-12 05:24:39 +00:00
* `log.Logger`: You can set this value to customize the global logger (the one used by package level methods).
2022-03-20 19:19:42 +00:00
* `zlog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zlog.Disabled` to disable logging altogether (quiet mode).
* `zlog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events.
* `zlog.TimestampFieldName`: Can be set to customize `Timestamp` field name.
* `zlog.LevelFieldName`: Can be set to customize level field name.
* `zlog.MessageFieldName`: Can be set to customize message field name.
* `zlog.ErrorFieldName`: Can be set to customize `Err` field name.
* `zlog.TimeFieldFormat`: Can be set to customize `Time` field value formatting. If set with `zlog.TimeFormatUnix`, `zlog.TimeFormatUnixMs` or `zlog.TimeFormatUnixMicro`, times are formated as UNIX timestamp.
* `zlog.DurationFieldUnit`: Can be set to customize the unit for time.Duration type fields added by `Dur` (default: `time.Millisecond`).
2022-03-20 19:31:02 +00:00
* `zlog.DurationFieldInteger`: If set to `true`, `Dur` fields are formatted as integers instead of floats (default: `false`).
2022-03-20 19:19:42 +00:00
* `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.
2017-05-12 05:24:39 +00:00
## Field Types
### Standard Types
* `Str`
* `Bool`
* `Int`, `Int8`, `Int16`, `Int32`, `Int64`
* `Uint`, `Uint8`, `Uint16`, `Uint32`, `Uint64`
* `Float32`, `Float64`
### Advanced Fields
2022-03-20 19:19:42 +00:00
* `Err`: Takes an `error` and renders it as a string using the `zlog.ErrorFieldName` field name.
* `Func`: Run a `func` only if the level is enabled.
2022-03-20 19:19:42 +00:00
* `Timestamp`: Inserts a timestamp field with `zlog.TimestampFieldName` field name, formatted using `zlog.TimeFieldFormat`.
* `Time`: Adds a field with time formatted with `zlog.TimeFieldFormat`.
* `Dur`: Adds a field with `time.Duration`.
2017-05-20 07:22:37 +00:00
* `Dict`: Adds a sub-key/value as a field of the event.
* `RawJSON`: Adds a field with an already encoded JSON (`[]byte`)
* `Hex`: Adds a field with value formatted as a hexadecimal string (`[]byte`)
2017-05-20 07:22:37 +00:00
* `Interface`: Uses reflection to marshal the type.
2017-05-12 05:24:39 +00:00
Most fields are also available in the slice format (`Strs` for `[]string`, `Errs` for `[]error` etc.)
## Binary Encoding
2022-03-20 19:19:42 +00:00
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:
2018-04-19 03:29:59 +00:00
```bash
go build -tags binary_log .
```
To Decode binary encoded log files you can use any CBOR decoder. One has been tested to work
2022-03-20 19:19:42 +00:00
with zlog library is [CSD](https://github.com/toravir/csd/).
2018-04-26 20:41:11 +00:00
## Related Projects
2022-03-20 19:19:42 +00:00
* [grpc-zlog](https://github.com/cheapRoc/grpc-zlog): Implementation of `grpclog.LoggerV2` interface using `zlog`
* [overlog](https://github.com/Trendyol/overlog): Implementation of `Mapped Diagnostic Context` interface using `zlog`
* [zlogr](https://github.com/go-logr/zlogr): Implementation of `logr.LogSink` interface using `zlog`
2018-04-26 20:41:11 +00:00
## Benchmarks
2017-05-20 09:03:07 +00:00
2018-09-18 09:18:32 +00:00
See [logbench](http://hackemist.com/logbench/) for more comprehensive and up-to-date benchmarks.
2017-05-20 09:03:07 +00:00
All operations are allocation free (those numbers *include* JSON encoding):
2018-04-19 03:29:59 +00:00
```text
BenchmarkLogEmpty-8 100000000 19.1 ns/op 0 B/op 0 allocs/op
BenchmarkDisabled-8 500000000 4.07 ns/op 0 B/op 0 allocs/op
BenchmarkInfo-8 30000000 42.5 ns/op 0 B/op 0 allocs/op
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
2017-05-20 09:03:07 +00:00
```
2022-03-20 19:19:42 +00:00
There are a few Go logging benchmarks and comparisons that include zlog.
2018-04-19 03:29:59 +00:00
* [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench)
* [uber-common/zap](https://github.com/uber-go/zap#performance)
Using Uber's zap comparison benchmark:
2017-05-20 09:03:07 +00:00
Log a message and 10 fields:
| Library | Time | Bytes Allocated | Objects Allocated |
| :--- | :---: | :---: | :---: |
2022-03-20 19:19:42 +00:00
| zlog | 767 ns/op | 552 B/op | 6 allocs/op |
2017-05-20 09:03:07 +00:00
| :zap: zap | 848 ns/op | 704 B/op | 2 allocs/op |
| :zap: zap (sugared) | 1363 ns/op | 1610 B/op | 20 allocs/op |
| go-kit | 3614 ns/op | 2895 B/op | 66 allocs/op |
| lion | 5392 ns/op | 5807 B/op | 63 allocs/op |
| logrus | 5661 ns/op | 6092 B/op | 78 allocs/op |
| apex/log | 15332 ns/op | 3832 B/op | 65 allocs/op |
| log15 | 20657 ns/op | 5632 B/op | 93 allocs/op |
Log a message with a logger that already has 10 fields of context:
| Library | Time | Bytes Allocated | Objects Allocated |
| :--- | :---: | :---: | :---: |
2022-03-20 19:19:42 +00:00
| zlog | 52 ns/op | 0 B/op | 0 allocs/op |
2017-05-20 09:03:07 +00:00
| :zap: zap | 283 ns/op | 0 B/op | 0 allocs/op |
| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op |
| lion | 2702 ns/op | 4074 B/op | 38 allocs/op |
| go-kit | 3378 ns/op | 3046 B/op | 52 allocs/op |
| logrus | 4309 ns/op | 4564 B/op | 63 allocs/op |
| apex/log | 13456 ns/op | 2898 B/op | 51 allocs/op |
| log15 | 14179 ns/op | 2642 B/op | 44 allocs/op |
Log a static string, without any context or `printf`-style templating:
| Library | Time | Bytes Allocated | Objects Allocated |
| :--- | :---: | :---: | :---: |
2022-03-20 19:19:42 +00:00
| zlog | 50 ns/op | 0 B/op | 0 allocs/op |
2017-05-20 09:03:07 +00:00
| :zap: zap | 236 ns/op | 0 B/op | 0 allocs/op |
| standard library | 453 ns/op | 80 B/op | 2 allocs/op |
| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op |
| go-kit | 508 ns/op | 656 B/op | 13 allocs/op |
| lion | 771 ns/op | 1224 B/op | 10 allocs/op |
| logrus | 1244 ns/op | 1505 B/op | 27 allocs/op |
| apex/log | 2751 ns/op | 584 B/op | 11 allocs/op |
| log15 | 5181 ns/op | 1592 B/op | 26 allocs/op |
## Caveats
2022-03-20 19:19:42 +00:00
Note that zlog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON:
```go
2022-03-20 19:19:42 +00:00
logger := zlog.New(os.Stderr).With().Timestamp().Logger()
logger.Info().
Timestamp().
Msg("dup")
// Output: {"level":"info","time":1494567715,"time":1494567715,"message":"dup"}
```
In this case, many consumers will take the last value, but this is not guaranteed; check yours if in doubt.