Convert Figma logo to code with AI

rs logozerolog

Zero Allocation JSON Logger

10,498
570
10,498
131

Top Related Projects

24,641

Structured, pluggable logging for Go.

21,865

Blazing fast, structured, leveled logging in Go.

3,539

Leveled execution logs for Go

1,365

Structured logging package for Go.

1,103

Structured, composable logging for Go

lumberjack is a log rolling package for Go

Quick Overview

Zerolog is a fast and simple logging library for Go, designed to provide zero-allocation JSON logging. It aims to offer high performance while maintaining a clean and easy-to-use API, making it suitable for both development and production environments.

Pros

  • Extremely fast and efficient, with zero-allocation JSON logging
  • Highly customizable with a wide range of options for formatting and output
  • Supports structured logging out of the box
  • Compatible with standard library's log package

Cons

  • May have a steeper learning curve for developers new to structured logging
  • JSON output by default, which might not be ideal for all use cases
  • Limited built-in support for non-JSON output formats
  • Requires explicit error checking, which can lead to more verbose code

Code Examples

  1. Basic logging:
package main

import (
    "github.com/rs/zerolog"
    "github.com/rs/zerolog/log"
)

func main() {
    log.Info().Msg("Hello, Zerolog!")
}
  1. Structured logging with fields:
log.Info().
    Str("name", "John").
    Int("age", 30).
    Msg("User logged in")
  1. Using a custom logger with context:
logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
ctx := logger.WithContext(context.Background())

logger.Info().Str("component", "server").Msg("Server started")
  1. Logging errors:
err := someFunction()
if err != nil {
    log.Error().Err(err).Msg("An error occurred")
}

Getting Started

To start using Zerolog in your Go project, follow these steps:

  1. Install the package:

    go get -u github.com/rs/zerolog/log
    
  2. Import and use in your code:

    package main
    
    import (
        "github.com/rs/zerolog"
        "github.com/rs/zerolog/log"
    )
    
    func main() {
        // Optional: Set global log level
        zerolog.SetGlobalLevel(zerolog.InfoLevel)
    
        // Optional: Set a custom time format
        zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
    
        // Start logging
        log.Info().Msg("Zerolog is now configured and ready to use!")
    }
    

With these steps, you'll have Zerolog set up and ready to use in your Go application.

Competitor Comparisons

24,641

Structured, pluggable logging for Go.

Pros of Logrus

  • More mature and widely adopted in the Go community
  • Extensive feature set, including hooks for custom output handling
  • Supports a variety of output formats (JSON, text, etc.)

Cons of Logrus

  • Generally slower performance compared to Zerolog
  • More memory allocations, which can impact high-performance applications
  • API is not as ergonomic for structured logging

Code Comparison

Logrus:

log.WithFields(log.Fields{
    "animal": "walrus",
    "size":   10,
}).Info("A group of walrus emerges from the ocean")

Zerolog:

log.Info().
    Str("animal", "walrus").
    Int("size", 10).
    Msg("A group of walrus emerges from the ocean")

Key Differences

  • Zerolog is designed for zero-allocation logging, making it more performant
  • Logrus uses a more traditional key-value pair approach, while Zerolog uses a fluent API
  • Zerolog focuses on structured logging by default, whereas Logrus supports both structured and unstructured logging
  • Zerolog has a smaller API surface, which can lead to a steeper learning curve but potentially fewer bugs
  • Logrus offers more built-in features out of the box, while Zerolog prioritizes performance and simplicity

Both libraries are popular choices for logging in Go, with Logrus being more established and feature-rich, while Zerolog offers better performance for high-throughput applications.

21,865

Blazing fast, structured, leveled logging in Go.

Pros of zap

  • Highly optimized for performance, often benchmarking faster than zerolog
  • Offers more flexibility in log level naming and custom levels
  • Provides built-in support for sampling logs

Cons of zap

  • More complex API, requiring more setup and configuration
  • Larger memory footprint compared to zerolog
  • Less intuitive for developers familiar with traditional logging patterns

Code Comparison

zerolog:

logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
logger.Info().Str("key", "value").Msg("Hello, World!")

zap:

logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("Hello, World!", zap.String("key", "value"))

Both zerolog and zap are popular logging libraries for Go, offering high-performance structured logging. zerolog focuses on simplicity and ease of use, while zap prioritizes flexibility and advanced features. The choice between them often depends on specific project requirements and developer preferences.

3,539

Leveled execution logs for Go

Pros of glog

  • Widely adopted and battle-tested in Google's production environments
  • Simple API with familiar log levels (INFO, WARNING, ERROR, FATAL)
  • Built-in support for command-line flags for configuration

Cons of glog

  • Lacks structured logging capabilities
  • Limited flexibility in output formatting
  • No support for JSON output, which is increasingly important for log aggregation systems

Code Comparison

glog:

import "github.com/golang/glog"

glog.Info("Starting application")
glog.Errorf("Failed to connect to database: %v", err)

zerolog:

import "github.com/rs/zerolog/log"

log.Info().Msg("Starting application")
log.Error().Err(err).Msg("Failed to connect to database")

Key Differences

  • zerolog focuses on zero-allocation logging and high performance
  • zerolog provides structured logging with JSON output by default
  • glog uses a global logger, while zerolog encourages creating logger instances
  • zerolog offers more flexibility in log formatting and output destinations
  • glog automatically handles log file rotation, while zerolog requires additional setup for this feature

Both libraries have their strengths, but zerolog is generally considered more modern and performant, especially for applications that benefit from structured logging and JSON output.

1,365

Structured logging package for Go.

Pros of apex/log

  • Simpler API with fewer concepts to learn
  • Built-in support for colored console output
  • Easier to get started with for basic logging needs

Cons of apex/log

  • Less performant compared to zerolog's zero-allocation approach
  • Fewer built-in formatters and output options
  • Limited support for structured logging compared to zerolog

Code Comparison

apex/log:

log.WithFields(log.Fields{
    "user": "jdoe",
    "action": "login",
}).Info("User logged in")

zerolog:

logger.Info().
    Str("user", "jdoe").
    Str("action", "login").
    Msg("User logged in")

Both libraries provide structured logging capabilities, but zerolog uses a more fluent API with method chaining. apex/log uses a more traditional approach with a single WithFields method.

zerolog offers better performance due to its zero-allocation design, making it more suitable for high-throughput applications. However, apex/log's simpler API and built-in color support make it easier to use for smaller projects or developers new to structured logging.

Choose apex/log for simplicity and ease of use, or zerolog for performance and more advanced structured logging features.

1,103

Structured, composable logging for Go

Pros of log15

  • More flexible and customizable logging interface
  • Supports logging contexts and child loggers
  • Offers a wider range of output formats, including JSON and logfmt

Cons of log15

  • Generally slower performance compared to zerolog
  • Less memory-efficient due to its interface-based design
  • Not as actively maintained as zerolog

Code Comparison

log15:

log := log15.New("module", "app/server")
log.Info("server started", "port", 8080)

zerolog:

log := zerolog.New(os.Stdout).With().Timestamp().Logger()
log.Info().Str("module", "app/server").Int("port", 8080).Msg("server started")

Key Differences

  • log15 uses a more traditional key-value pair approach for structured logging
  • zerolog employs a fluent API and method chaining for adding fields
  • zerolog is designed for zero-allocation logging, which contributes to its better performance
  • log15 offers more built-in handlers and formatters out of the box
  • zerolog has better integration with standard library's io.Writer interface

Both libraries provide structured logging capabilities, but zerolog focuses more on performance and efficiency, while log15 offers greater flexibility and customization options.

lumberjack is a log rolling package for Go

Pros of Lumberjack

  • Specialized in log file rotation and management
  • Simple and focused API for handling log files
  • Seamless integration with Go's standard library log package

Cons of Lumberjack

  • Limited to file-based logging only
  • Lacks advanced logging features like structured logging or log levels
  • No built-in performance optimizations for high-throughput logging

Code Comparison

Lumberjack:

log.SetOutput(&lumberjack.Logger{
    Filename:   "/var/log/myapp/foo.log",
    MaxSize:    500, // megabytes
    MaxBackups: 3,
    MaxAge:     28, // days
    Compress:   true,
})
log.Println("This is a log message")

Zerolog:

logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
logger.Info().Str("foo", "bar").Msg("Hello World")

Lumberjack focuses on log file management, while Zerolog provides a more comprehensive logging solution with structured logging and performance optimizations. Lumberjack is ideal for projects that primarily need log rotation, whereas Zerolog offers a broader set of logging features and better performance for high-volume logging scenarios.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Zero Allocation JSON Logger

godoc license Build Status Go Coverage

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. Its unique chaining API allows zerolog to write JSON (or CBOR) log events by avoiding allocations and reflection.

Uber's zap library pioneered this approach. Zerolog is taking this concept to the next level with a simpler to use API and even better performance.

To keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) zerolog.ConsoleWriter.

Pretty Logging Image

Who uses zerolog

Find out who uses zerolog and add your company / project to the list.

Features

Installation

go get -u github.com/rs/zerolog/log

Getting Started

Simple Logging Example

For simple logging, import the global logger package github.com/rs/zerolog/log

package main

import (
    "github.com/rs/zerolog"
    "github.com/rs/zerolog/log"
)

func main() {
    // UNIX Time is faster and smaller than most timestamps
    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

    log.Print("hello world")
}

// Output: {"time":1516134303,"level":"debug","message":"hello world"}

Note: By default log writes to os.Stderr Note: The default log level for log.Print is trace

Contextual Logging

zerolog allows data to be added to log messages in the form of key:value pairs. The data added to the message adds "context" about the log event that can be critical for debugging as well as myriad other purposes. An example of this is below:

package main

import (
    "github.com/rs/zerolog"
    "github.com/rs/zerolog/log"
)

func main() {
    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

    log.Debug().
        Str("Scale", "833 cents").
        Float64("Interval", 833.09).
        Msg("Fibonacci is everywhere")
    
    log.Debug().
        Str("Name", "Tom").
        Send()
}

// Output: {"level":"debug","Scale":"833 cents","Interval":833.09,"time":1562212768,"message":"Fibonacci is everywhere"}
// Output: {"level":"debug","Name":"Tom","time":1562212768}

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

Leveled Logging

Simple Leveled Logging Example

package main

import (
    "github.com/rs/zerolog"
    "github.com/rs/zerolog/log"
)

func main() {
    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

    log.Info().Msg("hello world")
}

// Output: {"time":1516134303,"level":"info","message":"hello world"}

It is very important to note that when using the zerolog chaining API, as shown above (log.Info().Msg("hello world"), the chain must have either the Msg or Msgf method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this.

zerolog allows for logging at the following levels (from highest to lowest):

  • panic (zerolog.PanicLevel, 5)
  • fatal (zerolog.FatalLevel, 4)
  • error (zerolog.ErrorLevel, 3)
  • warn (zerolog.WarnLevel, 2)
  • info (zerolog.InfoLevel, 1)
  • debug (zerolog.DebugLevel, 0)
  • trace (zerolog.TraceLevel, -1)

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

This example uses command-line flags to demonstrate various outputs depending on the chosen log level.

package main

import (
    "flag"

    "github.com/rs/zerolog"
    "github.com/rs/zerolog/log"
)

func main() {
    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
    debug := flag.Bool("debug", false, "sets log level to debug")

    flag.Parse()

    // Default level for this example is info, unless debug flag is present
    zerolog.SetGlobalLevel(zerolog.InfoLevel)
    if *debug {
        zerolog.SetGlobalLevel(zerolog.DebugLevel)
    }

    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")

    if e := log.Debug(); e.Enabled() {
        // Compute log output only if enabled.
        value := "bar"
        e.Str("foo", value).Msg("some debug message")
    }
}

Info Output (no flag)

$ ./logLevelExample
{"time":1516387492,"level":"info","message":"This message appears when log level set to Debug or Info"}

Debug Output (debug flag set)

$ ./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"}

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.

package main

import (
    "github.com/rs/zerolog"
    "github.com/rs/zerolog/log"
)

func main() {
    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

    log.Log().
        Str("foo", "bar").
        Msg("")
}

// Output: {"time":1494567715,"foo":"bar"}

Error Logging

You can log errors using the Err method

package main

import (
	"errors"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

func main() {
	zerolog.TimeFieldFormat = zerolog.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}

The default field name for errors is error, you can change this by setting zerolog.ErrorFieldName to meet your needs.

Error Logging with Stacktrace

Using github.com/pkg/errors, you can add a formatted stacktrace to your errors.

package main

import (
	"github.com/pkg/errors"
	"github.com/rs/zerolog/pkgerrors"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

func main() {
	zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
	zerolog.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}

zerolog.ErrorStackMarshaler must be set in order for the stack to output anything.

Logging Fatal Messages

package main

import (
    "errors"

    "github.com/rs/zerolog"
    "github.com/rs/zerolog/log"
)

func main() {
    err := errors.New("A repo man spends his life getting into tense situations")
    service := "myservice"

    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

    log.Fatal().
        Err(err).
        Str("service", service).
        Msgf("Cannot start %s", service)
}

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

NOTE: Using Msgf generates one allocation even when the logger is disabled.

Create logger instance to manage different outputs

logger := zerolog.New(os.Stderr).With().Timestamp().Logger()

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

sublogger := log.With().
                 Str("component", "foo").
                 Logger()
sublogger.Info().Msg("hello world")

// Output: {"level":"info","time":1494567715,"message":"hello world","component":"foo"}

Pretty logging

To log a human-friendly, colorized output, use zerolog.ConsoleWriter:

log.Logger = log.Output(zerolog.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:

output := zerolog.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))
}

log := zerolog.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

Sub dictionary

log.Info().
    Str("foo", "bar").
    Dict("dict", zerolog.Dict().
        Str("bar", "baz").
        Int("n", 1),
    ).Msg("hello world")

// Output: {"level":"info","time":1494567715,"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}

Customize automatic field names

zerolog.TimestampFieldName = "t"
zerolog.LevelFieldName = "l"
zerolog.MessageFieldName = "m"

log.Info().Msg("hello world")

// Output: {"l":"info","t":1494567715,"m":"hello world"}

Add contextual fields to the global logger

log.Logger = log.With().Str("foo", "bar").Logger()

Add file and line number to log

Equivalent of Llongfile:

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:

zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {
    return filepath.Base(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:

wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) {
		fmt.Printf("Logger Dropped %d messages", missed)
	})
log := zerolog.New(wr)
log.Print("test")

You will need to install code.cloudfoundry.org/go-diodes to use this feature.

Log Sampling

sampled := log.Sample(&zerolog.BasicSampler{N: 10})
sampled.Info().Msg("will be logged every 10 messages")

// Output: {"time":1494567715,"level":"info","message":"will be logged every 10 messages"}

More advanced sampling:

// Will let 5 debug messages per period of 1 second.
// Over 5 debug message, 1 every 100 debug messages are logged.
// Other levels are not sampled.
sampled := log.Sample(zerolog.LevelSampler{
    DebugSampler: &zerolog.BurstSampler{
        Burst: 5,
        Period: 1*time.Second,
        NextSampler: &zerolog.BasicSampler{N: 100},
    },
})
sampled.Debug().Msg("hello world")

// Output: {"time":1494567715,"level":"debug","message":"hello world"}

Hooks

type SeverityHook struct{}

func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
    if level != zerolog.NoLevel {
        e.Str("severity", level.String())
    }
}

hooked := log.Hook(SeverityHook{})
hooked.Warn().Msg("")

// Output: {"level":"warn","severity":"warn"}

Pass a sub-logger by context

ctx := log.With().Str("component", "module").Logger().WithContext(ctx)

log.Ctx(ctx).Info().Msg("hello world")

// Output: {"component":"module","level":"info","message":"hello world"}

Set as standard logger output

log := zerolog.New(os.Stdout).With().
    Str("foo", "bar").
    Logger()

stdlog.SetFlags(0)
stdlog.SetOutput(log)

stdlog.Print("hello world")

// Output: {"foo":"bar","message":"hello world"}

context.Context integration

Go contexts are commonly passed throughout Go code, and this can help you pass your Logger into places it might otherwise be hard to inject. The Logger instance may be attached to Go context (context.Context) using Logger.WithContext(ctx) and extracted from it using zerolog.Ctx(ctx). For example:

func f() {
    logger := zerolog.New(os.Stdout)
    ctx := context.Background()

    // Attach the Logger to the context.Context
    ctx = logger.WithContext(ctx)
    someFunc(ctx)
}

func someFunc(ctx context.Context) {
    // Get Logger from the go Context. if it's nil, then
    // `zerolog.DefaultContextLogger` is returned, if
    // `DefaultContextLogger` is nil, then a disabled logger is returned.
    logger := zerolog.Ctx(ctx)
    logger.Info().Msg("Hello")
}

A second form of context.Context integration allows you to pass the current context.Context into the logged event, and retrieve it from hooks. This can be useful to log trace and span IDs or other information stored in the go context, and facilitates the unification of logging and tracing in some systems:

type TracingHook struct{}

func (h TracingHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
    ctx := e.GetCtx()
    spanId := getSpanIdFromContext(ctx) // as per your tracing framework
    e.Str("span-id", spanId)
}

func f() {
    // Setup the logger
    logger := zerolog.New(os.Stdout)
    logger = logger.Hook(TracingHook{})

    ctx := context.Background()
    // Use the Ctx function to make the context available to the hook
    logger.Info().Ctx(ctx).Msg("Hello")
}

Integration with net/http

The github.com/rs/zerolog/hlog package provides some helpers to integrate zerolog with http.Handler.

In this example we use alice to install logger for better readability.

log := zerolog.New(os.Stdout).With().
    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.
// Thanks to that handler, all our logs will come with some prepopulated fields.
c = c.Append(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
    hlog.FromRequest(r).Info().
        Str("method", r.Method).
        Stringer("url", r.URL).
        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")

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

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.

func main() {
	consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout}

	multi := zerolog.MultiLevelWriter(consoleWriter, os.Stdout)

	logger := zerolog.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!"}

Global Settings

Some settings can be changed and will be applied to all loggers:

  • log.Logger: You can set this value to customize the global logger (the one used by package level methods).
  • zerolog.SetGlobalLevel: Can raise the minimum level of all loggers. Call this with zerolog.Disabled to disable logging altogether (quiet mode).
  • zerolog.DisableSampling: If argument is true, all sampled loggers will stop sampling and issue 100% of their log events.
  • zerolog.TimestampFieldName: Can be set to customize Timestamp field name.
  • zerolog.LevelFieldName: Can be set to customize level field name.
  • zerolog.MessageFieldName: Can be set to customize message field name.
  • zerolog.ErrorFieldName: Can be set to customize Err field name.
  • zerolog.TimeFieldFormat: Can be set to customize Time field value formatting. If set with zerolog.TimeFormatUnix, zerolog.TimeFormatUnixMs or zerolog.TimeFormatUnixMicro, times are formatted as UNIX timestamp.
  • zerolog.DurationFieldUnit: Can be set to customize the unit for time.Duration type fields added by Dur (default: time.Millisecond).
  • zerolog.DurationFieldInteger: If set to true, Dur fields are formatted as integers instead of floats (default: false).
  • zerolog.ErrorHandler: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking.
  • zerolog.FloatingPointPrecision: If set to a value other than -1, controls the number of digits when formatting float numbers in JSON. See strconv.FormatFloat for more details.

Field Types

Standard Types

  • Str
  • Bool
  • Int, Int8, Int16, Int32, Int64
  • Uint, Uint8, Uint16, Uint32, Uint64
  • Float32, Float64

Advanced Fields

  • 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.
  • Timestamp: Inserts a timestamp field with zerolog.TimestampFieldName field name, formatted using zerolog.TimeFieldFormat.
  • Time: Adds a field with time formatted with zerolog.TimeFieldFormat.
  • Dur: Adds a field with time.Duration.
  • Dict: Adds a sub-key/value as a field of the event.
  • RawJSON: Adds a field with an already encoded JSON ([]byte)
  • Hex: Adds a field with value formatted as a hexadecimal string ([]byte)
  • Interface: Uses reflection to marshal the type.

Most fields are also available in the slice format (Strs for []string, Errs for []error etc.)

Binary Encoding

In addition to the default JSON encoding, zerolog can produce binary logs using CBOR encoding. The choice of encoding can be decided at compile time using the build tag binary_log as follows:

go build -tags binary_log .

To Decode binary encoded log files you can use any CBOR decoder. One has been tested to work with zerolog library is CSD.

Related Projects

  • grpc-zerolog: Implementation of grpclog.LoggerV2 interface using zerolog
  • overlog: Implementation of Mapped Diagnostic Context interface using zerolog
  • zerologr: Implementation of logr.LogSink interface using zerolog

Benchmarks

See logbench for more comprehensive and up-to-date benchmarks.

All operations are allocation free (those numbers include JSON encoding):

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

There are a few Go logging benchmarks and comparisons that include zerolog.

Using Uber's zap comparison benchmark:

Log a message and 10 fields:

LibraryTimeBytes AllocatedObjects Allocated
zerolog767 ns/op552 B/op6 allocs/op
:zap: zap848 ns/op704 B/op2 allocs/op
:zap: zap (sugared)1363 ns/op1610 B/op20 allocs/op
go-kit3614 ns/op2895 B/op66 allocs/op
lion5392 ns/op5807 B/op63 allocs/op
logrus5661 ns/op6092 B/op78 allocs/op
apex/log15332 ns/op3832 B/op65 allocs/op
log1520657 ns/op5632 B/op93 allocs/op

Log a message with a logger that already has 10 fields of context:

LibraryTimeBytes AllocatedObjects Allocated
zerolog52 ns/op0 B/op0 allocs/op
:zap: zap283 ns/op0 B/op0 allocs/op
:zap: zap (sugared)337 ns/op80 B/op2 allocs/op
lion2702 ns/op4074 B/op38 allocs/op
go-kit3378 ns/op3046 B/op52 allocs/op
logrus4309 ns/op4564 B/op63 allocs/op
apex/log13456 ns/op2898 B/op51 allocs/op
log1514179 ns/op2642 B/op44 allocs/op

Log a static string, without any context or printf-style templating:

LibraryTimeBytes AllocatedObjects Allocated
zerolog50 ns/op0 B/op0 allocs/op
:zap: zap236 ns/op0 B/op0 allocs/op
standard library453 ns/op80 B/op2 allocs/op
:zap: zap (sugared)337 ns/op80 B/op2 allocs/op
go-kit508 ns/op656 B/op13 allocs/op
lion771 ns/op1224 B/op10 allocs/op
logrus1244 ns/op1505 B/op27 allocs/op
apex/log2751 ns/op584 B/op11 allocs/op
log155181 ns/op1592 B/op26 allocs/op

Caveats

Field duplication

Note that zerolog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON:

logger := zerolog.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.

Concurrency safety

Be careful when calling UpdateContext. It is not concurrency safe. Use the With method to create a child logger:

func handler(w http.ResponseWriter, r *http.Request) {
    // Create a child logger for concurrency safety
    logger := log.Logger.With().Logger()

    // Add context fields, for example User-Agent from HTTP headers
    logger.UpdateContext(func(c zerolog.Context) zerolog.Context {
        ...
    })
}