Zero Allocation JSON Logger


Zero Allocation JSON Logger

godoc license Build Status 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.



go get -u

Getting Started

Simple Logging Example

For simple logging, import the global logger package

package main

import (

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 debug

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 (

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

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

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

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 (


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


    // Default level for this example is info, unless debug flag is present
    if *debug {

    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 (

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

        Str("foo", "bar").

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

Error Logging

You can log errors using the Err method

package main

import (


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

	err := errors.New("seems we have an error here")

// 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, you can add a formatted stacktrace to your errors.

package main

import (


func main() {
	zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
	zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack

	err := outer()

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 (


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

    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

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

    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

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

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 follow:

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

You will need to install 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"}


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{})

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


stdlog.Print("hello world")

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

Integration with net/http

The 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().
    Str("role", "my-service").
    Str("host", host).

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) {
        Str("method", r.Method).
        Stringer("url", r.URL).
        Int("status", status).
        Int("size", size).
        Dur("duration", duration).
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.
        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 by applied to all loggers:

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

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.
  • 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


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:

Library Time Bytes Allocated Objects Allocated
zerolog 767 ns/op 552 B/op 6 allocs/op
zap 848 ns/op 704 B/op 2 allocs/op
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
zerolog 52 ns/op 0 B/op 0 allocs/op
zap 283 ns/op 0 B/op 0 allocs/op
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
zerolog 50 ns/op 0 B/op 0 allocs/op
zap 236 ns/op 0 B/op 0 allocs/op
standard library 453 ns/op 80 B/op 2 allocs/op
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


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()
// 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.

  • Refactored zerolog.ConsoleWriter to allow customization

    Refactored zerolog.ConsoleWriter to allow customization

    As outlined in, this patch refactors the zerolog.ConsoleWriter in two ways:

    • The default formatting has been changed to be more sparse and visually attractive
    • The formatting logic has been extracted to separate functions, so it can be changed from the user code

    I had to change the design of the prototype in order to maintain the backwards compatibility: the prototype has defined default formatting functions (formatters) on the concrete instance of ConsoleWriter, but without using an initializer, these would be empty. Therefore, I've added a number of defensive checks into ConsoleWriter.Write(), and a ConsoleWriter.Reset() method. This is not ideal, but I agree that maintaining backwards compatibility is an important goal, and the behaviour is predictable in my testing.

    I've added a benchmark test to make sure I inadverently don't harm the performance: the performance has stayed roughly the same. The tests and examples have been run with the -race parameter.

    I've updated the screenshot to reflect the new look, and added a comprehensive example to the README.

    opened by karmi 26
  • Binary format support

    Binary format support

    Submitting the PR for #21 with two minor things in the todo items:

    1. Changes to documentation ( Because after code review, will write the docs.

    2. When doing reflection, skip using JSON and write a binary based encoder Writing an equivalent of json.Marshal() would take more time and careful testing.

    opened by toravir 21
  • Teach zerolog how to return errors, with and without stack traces

    Teach zerolog how to return errors, with and without stack traces

    When zerolog logs an error message with an Error() finalizer, it returns a error. If the StackTrace() event has been called, the error will be a wrapped error using and will include the stack trace.

    There are a few subtle differences introduced with this change:

    1. It is possible to defeat this behavior using the Fields() method.
    2. Only one error can be handled by an Event at a time.

    Time was spent considering introducing an accumulator for errors that would be evaluated at finalizer-time, but this seemed unnecessary given errors should be wrapped and multiple calls to Err() seemed unlikely in practice.

    The behavior of the Msg() finalizer was left in tact in order to avoid any performance penalty in non-error handling conditions. The deferral of error handling can best be observed by looking at the performance hit of an Err() Event with and without StackTrace():

    BenchmarkErrorContextFields-8                  	20000000	        84.8 ns/op
    BenchmarkErrorContextFields_WithStackTrace-8   	  500000	      2552 ns/op
    BenchmarkLogContextFields-8                    	30000000	        47.6 ns/op
    ok	4.642s

    Fixes: #9

    opened by sean- 21
  • Context.Stack() not working

    Context.Stack() not working

    What happened: Using Context.Stack().Logger() does not work, the stack is not added to each log entries.

    What you expected to happen: The stack field should be added to each log entries

    How to reproduce it (as minimally and precisely as possible):

    package main
    import (
    func myFunc() {
    	err := errors.New("my error")
    	err = errors.WithStack(errors.Wrap(err, "something failed"))
    	log.Error().Err(err).Msg("hello world")
    func main() {
    	zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
    	log.Logger = log.With().Str("my", "field").Stack().Logger()

    Anything else we need to know?:

    I think it comes from the fact that Context.Stack() setup an Hook which is called after the event is completely built, so Err never see that Stack() was enabled. We can see it because the following example works as expected:

    package main
    import (
    func myFunc() {
    	err := errors.New("my error")
    	err = errors.WithStack(errors.Wrap(err, "something failed"))
    	log.Error().Stack().Err(err).Msg("hello world")
    func main() {
    	zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
    	log.Logger = log.With().Str("my", "field").Logger()

    I'm not sure how to fix this. One solution could be to add a stack field to Logger which would be transferred to the event in logger.newEvent.

    opened by skerkour-dev 19
  • Add context hook support

    Add context hook support

    I've got an idea to retranslate logger messages to Opentracing. It needs to add some mechanics to be able to propagate the span context from context.Context to the logger.

    opened by ndk 18
  • Add support for stack trace extration of error fields

    Add support for stack trace extration of error fields

    Proposal for #11.

    @sean-: what do you think about this implementation?

    I'm not super happy of the API. I'm not sure having Stack and Err separated is great design. What would you think about a new set of error-with-stack methods that would package the error message and the stack together.

    For instance:

    log.Log().ErrStack("error", err).Msg("")

    would generate:

    {"error": {"message": "error message", "stack": [{...}, {...}]}}
    opened by rs 18
  • Updates to to help with readability

    Updates to to help with readability

    Hey - I've recently decided to switch to zerolog and wanted to try and help by adding some organization to the file. I love the logger so far! As I'm teaching myself the library and learning the APIs, it seems like there's some room for improvement in the instructions for the layman (that would be me)... I have more edits I'd like to make as I go, but wanted to see if you considered this helpful before I spent more time on it! Thanks for the logger and your consideration!

    You can see the changes fully realized at my fork, which may be easier to read than all the code merge:


    opened by gilcrest 14
  • Add TraceLevel

    Add TraceLevel

    Sometimes you want finer-grained informational events and need to debug something that outputs way too much data to log outside of a specific build when you're targeting that particular thing and do not care about errors or other logging info (since the volume of trace info will obscure them).

    I think this could encroach on loggers like journald and that's why I'm asking for your opinion on adding this new log level.

    opened by crazy-max 13
  • The ConsoleWriter doesn't work well  on windows10

    The ConsoleWriter doesn't work well on windows10

    The Code:


    The messy output in Windows 10 (git bash & powershell & cmd): image

    And it‘s normal in Linux。 image

    It seems like the spaces are not displayed properly...

    help wanted 
    opened by Alecyrus 12
  • export buf

    export buf

    While using hook capability, in my use case, I had to access buf member in zerolog.Event struct, which is currently available only using reflection, which affects the performance.

    opened by evgenigourvitch 10
  • default output to stdout

    default output to stdout


    I spent an hour or so debugging zerolog, so let's see if i'm wrong or there is a bug :-)

    In the sample application code (without testing.T to keep it as simple as possible) below, the default output does not go to stderr, but stdout. When I debug, I do see initialization within zerolog to stderr, but the end result is not in stderr...

    package main
    import (
    func captureStderr(f func()) (string, error) {
    	var errOccurred error // in case an error occurred
    	old := os.Stderr      // keep backup of the real stderr
    	r, w, err := os.Pipe()
    	if err != nil {
    		return "", err
    	os.Stderr = w
    	outC := make(chan string)
    	// copy the output in a separate goroutine so printing can't block indefinitely
    	go func() {
    		var buf bytes.Buffer
    		_, cpErr := io.Copy(&buf, r)
    		if cpErr != nil {
    			errOccurred = cpErr
    		outC <- buf.String()
    	// calling function which stderr we are going to capture:
    	// back to normal state
    	err = w.Close()
    	if err != nil {
    		_, err = old.Write([]byte("Could not close file, error: " + err.Error()))
    		if err != nil {
    			errOccurred = err
    	os.Stderr = old // restoring the real stderr
    	if errOccurred != nil {
    		fmt.Printf("CaptureStderr, error occurred: %v\n", err)
    	return <-outC, nil
    func main() {
    	stdErr, err := captureStderr(func() {
    	if err != nil {
    		fmt.Println("error: " + err.Error())
    	if !strings.Contains(stdErr, "sw") {
    		fmt.Println("stderr does not contain, output: " + stdErr)
    	} else {
    		fmt.Println("ok, stderr contains: " + stdErr)
    module "awesomeProject"
    go 1.14
    require ( v1.19.0
    opened by stephanwesten 9
  • Add Any field function for any value

    Add Any field function for any value

    Go introduced any type, that is just an empty interface under the hood. I think it would be good to introduce Any() function in zerolog as well. Under the hood it will use the old Interface() function.


    // before
    log.Debug().Interface("params", p).Msg("charge request")
    // after
    log.Debug().Any("params", p).Msg("charge request")

    It makes the line a bit shorter and, in my opinion, makes it more obvious of what it's going to log.

    Also I don't propose to removeInterface() function, I propose to add a new function that's going to do the same thing that the old function did.

    opened by dils2k 0
  • Loop error when write log to kafka fail

    Loop error when write log to kafka fail

    I create a multi writer to file and to kafka as in project

    The implement of kafka is :

    Problem is when kafka server is down, the diode.poll() loop infinite so it write log a lot

    func (kw *KafkaLogWriter) Write(p []byte) (n int, err error) {
    	m := kafka.Message{
    		Value: p,
    	err = kw.WriteMessages(context.Background(), m)
    	if err != nil {
    		log.Printf("failed to write log message to kafka topic:")
    		return 0, err
    	return len(p), nil

    I also want to ask how this infinite for break ,

    func (dw Writer) poll() {
    	defer close(dw.done)
    	for {
    		d := dw.d.Next() // -----> when debug, in normal case it out of for loop here, when kafka error, it loop infinite
    		if d == nil {
    		p := *(*[]byte)(d)
    		// Proper usage of a sync.Pool requires each entry to have approximately
    		// the same memory cost. To obtain this property when the stored type
    		// contains a variably-sized buffer, we add a hard limit on the maximum buffer
    		// to place back in the pool.
    		// See
    		const maxSize = 1 << 16 // 64KiB
    		if cap(p) <= maxSize {
    opened by vuhoanghiep1993 0
  • Bump actions/cache from 3.0.5 to 3.2.2

    Bump actions/cache from 3.0.5 to 3.2.2

    Bumps actions/cache from 3.0.5 to 3.2.2.

    Release notes

    Sourced from actions/cache's releases.


    What's Changed

    New Contributors

    Full Changelog:


    What's Changed

    Full Changelog:


    What's Changed

    New Contributors

    ... (truncated)


    Sourced from actions/cache's changelog.


    • Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit. (PR)


    • Fixed #809 - zstd -d: no such file or directory error
    • Fixed #833 - cache doesn't work with github workspace directory


    • Fixed #810 - download stuck issue. A new timeout is introduced in the download process to abort the download if it gets stuck and doesn't finish within an hour.


    • Fix zstd not working for windows on gnu tar in issues #888 and #891.
    • Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable SEGMENT_DOWNLOAD_TIMEOUT_MINS. Default is 60 minutes.


    • Enhanced the warning message for cache unavailablity in case of GHES.


    • Fix a bug with sorting inputs.
    • Update definition for restore-keys in


    • Update toolkit version to 3.0.5 to include @actions/[email protected]^1.10.0
    • Update @actions/cache to use updated saveState and setOutput functions from @actions/[email protected]^1.10.0


    • Update @actions/cache on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. (issue)


    • Added support for fallback to gzip to restore old caches on windows.


    • Bug fixes for bsdtar fallback if gnutar not available and gzip fallback if cache saved using old cache action on windows.


    • Added two new actions - restore and save for granular control on cache.


    • Released the two new actions - restore and save for granular control on cache


    • Update @actions/cache on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. (issue)
    • Added support for fallback to gzip to restore old caches on windows.
    • Added logs for cache version in case of a cache miss.


    • Reverted the changes made in 3.2.1 to use gnu tar and zstd by default on windows.
    • 4723a57 Revert compression changes related to windows but keep version logging (#1049)
    • d1507cc Merge pull request #1042 from me-and/correct-readme-re-windows
    • 3337563 Merge branch 'main' into correct-readme-re-windows
    • 60c7666 save/ Fix typo in example (#1040)
    • b053f2b Fix formatting error in restore/ (#1044)
    • 501277c remove outdated Windows cache tip link
    • c1a5de8 Upgrade codeql to v2 (#1023)
    • 9b0be58 Release compression related changes for windows (#1039)
    • c17f4bf GA for granular cache (#1035)
    • ac25611 docs: fix an invalid link in (#929)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.

    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies github_actions 
    opened by dependabot[bot] 0
  • Output from Logger.Write always has a nil level

    Output from Logger.Write always has a nil level

    I've been using to emit error logs from and as the stderr for, so that output all goes to the same place.

    In both of those cases the level of the log messages is always nil, which I guess makes sense because nothing is setting the level.

    Is there some way to set a default level for Logger.Write? Any suggestions for how I might be able to set a level on these log lines? Thanks!

    opened by dnephin 0
  • Matching caller path in both json and flat line logs

    Matching caller path in both json and flat line logs


    Just a suggestion. Would it be better to replace example code here as the one below so that the callers matches in json and flat line logs? e.g. some/path/to/file.go:123 (no forward slash at the beginning which matches json version)



    zerolog.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:]
        file = short
        return file + ":" + strconv.Itoa(line)


    zerolog.CallerMarshalFunc = func(_ uintptr, file string, line int) string {
    	p, _ := os.Getwd()
    	return fmt.Sprintf("%s:%d", strings.TrimPrefix(file, p+"/"), line)
    opened by bentcoder 0
Olivier Poitrey
Director of Engineering at Netflix Co-Founder & ex-CTO of Dailymotion Co-Founder of NextDNS
Olivier Poitrey
Dead simple, super fast, zero allocation and modular logger for Golang

Onelog Onelog is a dead simple but very efficient JSON logger. It is one of the fastest JSON logger out there. Also, it is one of the logger with the

Francois Parquet 402 Sep 26, 2022
A powerful zero-dependency json logger.

ZKits Logger Library About This package is a library of ZKits project. This is a zero-dependency standard JSON log library that supports structured JS

Qingshan Luo 23 Dec 14, 2022
Convenient Logger interface and std logger wrapper

Convenient logger interface and wrapper around std logger Interface type Logger interface { Error(err error) Debugf(format string, args ...interface

Denis Mitrofanov 1 Nov 28, 2021
Logger - Simple logger without written with std pkg

Go-Logger Simple usage is: package main

MaskedTrench 2 Jan 2, 2022
Logger - A thin wrapper of uber-go/zap logger for personal project

a thin wraper of uber-go/zap logger for personal project 0. thanks uber-go/zap B

tsingson 0 Sep 17, 2022
A simple Go JSON logger.

logger A simple JSON logger for Go. It uses a context.Context to store values which will then be logged along with each message. It is possible to rec

Shawn Milochik 2 Jul 25, 2022
This package enables json output, level logging and so on to standard go logger.

logplug This package enables json output, level logging and so on to standard logger. Usage log.SetOutput(logplug.NewJSONPlug(os.Stderr, logplug.LogF

Koumei Mikuni 0 Dec 27, 2021
A logger, for Go

Go-Log A logger, for Go! It's sort of log and compatible, so in most cases can be used without any code changes. Breaking cha

Ian Kent 40 Oct 7, 2022
Simple logger for Go programs. Allows custom formats for messages.

go-logger A simple go logger for easy logging in your programs. Allows setting custom format for messages. Preview Install go get

Amanpreet Singh 283 Dec 17, 2022
Loggly Hooks for GO Logrus logger

Loggly Hooks for Logrus Usage package main import ( "" "" ) var logglyToken string = "YOUR_LOG

Sebest 28 Sep 26, 2022
A 12-factor app logger built for performance and happy development

logxi log XI is a structured 12-factor app logger built for speed and happy development. Simpler. Sane no-configuration defaults out of the box. Faste

Mario Gutierrez 349 Nov 27, 2022
A logger for Go SQL database driver without modify existing *sql.DB stdlib usage.

SQLDB-Logger A logger for Go SQL database driver without modify existing *sql.DB stdlib usage. Colored console writer output above only for sample/dev

Sarjono Mukti Aji 278 Jan 3, 2023
xlog is a logger for net/context aware HTTP applications

⚠️ Check zerolog, the successor of xlog. HTTP Handler Logger xlog is a logger for net/context aware HTTP applications. Unlike most loggers, xlog will

Olivier Poitrey 137 Sep 26, 2022
Configurable Logger for Go

Timber! This is a logger implementation that supports multiple log levels, multiple output destinations with configurable formats and levels for each.

DeNA SF 66 Jun 28, 2022
A feature-rich and easy to use logger for golang

A feature-rich and easy to use logger for golang ?? Install ?? Common Logs lumber.Success() lumber.Info() lumber.Debug() lumber.Warning()

Matthew Gleich 51 Dec 31, 2022
A minimal and extensible structured logger

⚠️ PRE-RELEASE ⚠️ DO NOT IMPORT THIS MODULE YOUR PROJECT WILL BREAK package log package log provides a minimal interface for structured logging in ser

Go kit 135 Jan 7, 2023
HTTP request logger for Golang

Horus ?? Introduction Horus is a request logger and viewer for Go. It allows developers log and view http requests made to their web application. Inst

Michael Okoh 81 Dec 27, 2022
Simple Yet Powerful Logger

sypl sypl provides a Simple Yet Powerful Logger built on top of the Golang sypl. A sypl logger can have many Outputs, and each Output is responsible f

Sauce Labs 8 Sep 23, 2022
simple concurrent logger

XMUS-LOGGER pure golang logger compatible with golang io standards. USAGE : logOptions := logger.LoggerOptions{ LogLevel: 6, // read more about lo

amupxm [amir hossein mokarrami far] 6 Aug 1, 2022