zerolog

package module
v1.28.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2022 License: MIT Imports: 23 Imported by: 1

README

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.

Features

Installation

go get -u github.com/DRK-Blutspende-BaWueHe/zerolog-for-logcom/log

Getting Started

Simple Logging Example

For simple logging, import the global logger package github.com/DRK-Blutspende-BaWueHe/zerolog-for-logcom/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 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 (
    "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 {
    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:

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

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

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

Caveats

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.

Documentation

Overview

Package zerolog provides a lightweight logging library dedicated to JSON logging.

A global Logger can be use for simple logging:

import "github.com/DRK-Blutspende-BaWueHe/zerolog-for-logcom/log"

log.Info().Msg("hello world")
// Output: {"time":1494567715,"level":"info","message":"hello world"}

NOTE: To import the global logger, import the "log" subpackage "github.com/DRK-Blutspende-BaWueHe/zerolog-for-logcom/log".

Fields can be added to log messages:

log.Info().Str("foo", "bar").Msg("hello world")
// Output: {"time":1494567715,"level":"info","message":"hello world","foo":"bar"}

Create logger instance to manage different outputs:

logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
logger.Info().
       Str("foo", "bar").
       Msg("hello world")
// Output: {"time":1494567715,"level":"info","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: {"time":1494567715,"level":"info","message":"hello world","component":"foo"}

Level logging

zerolog.SetGlobalLevel(zerolog.InfoLevel)

log.Debug().Msg("filtered out message")
log.Info().Msg("routed message")

if e := log.Debug(); e.Enabled() {
    // Compute log output only if enabled.
    value := compute()
    e.Str("foo": value).Msg("some debug message")
}
// Output: {"level":"info","time":1494567715,"routed message"}

Customize automatic field names:

log.TimestampFieldName = "t"
log.LevelFieldName = "p"
log.MessageFieldName = "m"

log.Info().Msg("hello world")
// Output: {"t":1494567715,"p":"info","m":"hello world"}

Log with no level and message:

log.Log().Str("foo","bar").Msg("")
// Output: {"time":1494567715,"foo":"bar"}

Add contextual fields to global Logger:

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

Sample logs:

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

Log with contextual hooks:

// Create the hook:
type SeverityHook struct{}

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

// And use it:
var h SeverityHook
log := zerolog.New(os.Stdout).Hook(h)
log.Warn().Msg("")
// Output: {"level":"warn","severity":"warn"}

Caveats

There is no fields deduplication out-of-the-box. Using the same key multiple times creates new key in final JSON each time.

logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
logger.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.

Index

Examples

Constants

View Source
const (
	// TimeFormatUnix defines a time format that makes time fields to be
	// serialized as Unix timestamp integers.
	TimeFormatUnix = ""

	// TimeFormatUnixMs defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in milliseconds.
	TimeFormatUnixMs = "UNIXMS"

	// TimeFormatUnixMicro defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in microseconds.
	TimeFormatUnixMicro = "UNIXMICRO"

	// TimeFormatUnixNano defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in nanoseconds.
	TimeFormatUnixNano = "UNIXNANO"
)

Variables

View Source
var (
	// TimestampFieldName is the field name used for the timestamp field.
	TimestampFieldName = "time"

	// LevelFieldName is the field name used for the level field.
	LevelFieldName = "level"

	// LevelTraceValue is the value used for the trace level field.
	LevelTraceValue = "trace"
	// LevelDebugValue is the value used for the debug level field.
	LevelDebugValue = "debug"
	// LevelInfoValue is the value used for the info level field.
	LevelInfoValue = "info"
	// LevelWarnValue is the value used for the warn level field.
	LevelWarnValue = "warn"
	// LevelErrorValue is the value used for the error level field.
	LevelErrorValue = "error"
	// LevelFatalValue is the value used for the fatal level field.
	LevelFatalValue = "fatal"
	// LevelPanicValue is the value used for the panic level field.
	LevelPanicValue = "panic"

	// LevelFieldMarshalFunc allows customization of global level field marshaling.
	LevelFieldMarshalFunc = func(l Level) string {
		return l.String()
	}

	// MessageFieldName is the field name used for the message field.
	MessageFieldName = "message"

	// ErrorFieldName is the field name used for error fields.
	ErrorFieldName = "error"

	// CallerFieldName is the field name used for caller field.
	CallerFieldName = "caller"

	// CallerSkipFrameCount is the number of stack frames to skip to find the caller.
	CallerSkipFrameCount = 2

	// CallerMarshalFunc allows customization of global caller marshaling
	CallerMarshalFunc = func(pc uintptr, file string, line int) string {
		return file + ":" + strconv.Itoa(line)
	}

	// ErrorStackFieldName is the field name used for error stacks.
	ErrorStackFieldName = "stack"

	// ErrorStackMarshaler extract the stack from err if any.
	ErrorStackMarshaler func(err error) interface{}

	// ErrorMarshalFunc allows customization of global error marshaling
	ErrorMarshalFunc = func(err error) interface{} {
		return err
	}

	// InterfaceMarshalFunc allows customization of interface marshaling.
	// Default: "encoding/json.Marshal"
	InterfaceMarshalFunc = json.Marshal

	// TimeFieldFormat defines the time format of the Time field type. If set to
	// TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX
	// timestamp as integer.
	TimeFieldFormat = time.RFC3339

	// TimestampFunc defines the function called to generate a timestamp.
	TimestampFunc = time.Now

	// DurationFieldUnit defines the unit for time.Duration type fields added
	// using the Dur method.
	DurationFieldUnit = time.Millisecond

	// DurationFieldInteger renders Dur fields as integer instead of float if
	// set to true.
	DurationFieldInteger = false

	// ErrorHandler is called whenever zerolog fails to write an event on its
	// output. If not set, an error is printed on the stderr. This handler must
	// be thread safe and non-blocking.
	ErrorHandler func(err error)

	// DefaultContextLogger is returned from Ctx() if there is no logger associated
	// with the context.
	DefaultContextLogger *Logger
)
View Source
var (
	// Often samples log every ~ 10 events.
	Often = RandomSampler(10)
	// Sometimes samples log every ~ 100 events.
	Sometimes = RandomSampler(100)
	// Rarely samples log every ~ 1000 events.
	Rarely = RandomSampler(1000)
)

Functions

func ConsoleTestWriter added in v1.26.3

func ConsoleTestWriter(t TestingLog) func(w *ConsoleWriter)

ConsoleTestWriter creates an option that correctly sets the file frame depth for testing.TB log.

func DisableSampling

func DisableSampling(v bool)

DisableSampling will disable sampling in all Loggers if true.

func SetGlobalLevel

func SetGlobalLevel(l Level)

SetGlobalLevel sets the global override for log level. If this values is raised, all Loggers will use at least this value.

To globally disable logs, set GlobalLevel to Disabled.

func SyncWriter

func SyncWriter(w io.Writer) io.Writer

SyncWriter wraps w so that each call to Write is synchronized with a mutex. This syncer can be used to wrap the call to writer's Write method if it is not thread safe. Note that you do not need this wrapper for os.File Write operations on POSIX and Windows systems as they are already thread-safe.

Types

type Array added in v1.1.0

type Array struct {
	// contains filtered or unexported fields
}

Array is used to prepopulate an array of items which can be re-used to add to log messages.

func Arr added in v1.1.0

func Arr() *Array

Arr creates an array to be added to an Event or Context.

func (*Array) Bool added in v1.1.0

func (a *Array) Bool(b bool) *Array

Bool append append the val as a bool to the array.

func (*Array) Bytes added in v1.1.0

func (a *Array) Bytes(val []byte) *Array

Bytes append append the val as a string to the array.

func (*Array) Dict added in v1.26.3

func (a *Array) Dict(dict *Event) *Array

Dict adds the dict Event to the array

func (*Array) Dur added in v1.1.0

func (a *Array) Dur(d time.Duration) *Array

Dur append append d to the array.

func (*Array) Err added in v1.1.0

func (a *Array) Err(err error) *Array

Err serializes and appends the err to the array.

func (*Array) Float32 added in v1.1.0

func (a *Array) Float32(f float32) *Array

Float32 append append f as a float32 to the array.

func (*Array) Float64 added in v1.1.0

func (a *Array) Float64(f float64) *Array

Float64 append append f as a float64 to the array.

func (*Array) Hex added in v1.6.0

func (a *Array) Hex(val []byte) *Array

Hex append append the val as a hex string to the array.

func (*Array) IPAddr added in v1.7.0

func (a *Array) IPAddr(ip net.IP) *Array

IPAddr adds IPv4 or IPv6 address to the array

func (*Array) IPPrefix added in v1.7.0

func (a *Array) IPPrefix(pfx net.IPNet) *Array

IPPrefix adds IPv4 or IPv6 Prefix (IP + mask) to the array

func (*Array) Int added in v1.1.0

func (a *Array) Int(i int) *Array

Int append append i as a int to the array.

func (*Array) Int16 added in v1.1.0

func (a *Array) Int16(i int16) *Array

Int16 append append i as a int16 to the array.

func (*Array) Int32 added in v1.1.0

func (a *Array) Int32(i int32) *Array

Int32 append append i as a int32 to the array.

func (*Array) Int64 added in v1.1.0

func (a *Array) Int64(i int64) *Array

Int64 append append i as a int64 to the array.

func (*Array) Int8 added in v1.1.0

func (a *Array) Int8(i int8) *Array

Int8 append append i as a int8 to the array.

func (*Array) Interface added in v1.1.0

func (a *Array) Interface(i interface{}) *Array

Interface append append i marshaled using reflection.

func (*Array) MACAddr added in v1.7.0

func (a *Array) MACAddr(ha net.HardwareAddr) *Array

MACAddr adds a MAC (Ethernet) address to the array

func (*Array) MarshalZerologArray added in v1.1.0

func (*Array) MarshalZerologArray(*Array)

MarshalZerologArray method here is no-op - since data is already in the needed format.

func (*Array) Object added in v1.1.0

func (a *Array) Object(obj LogObjectMarshaler) *Array

Object marshals an object that implement the LogObjectMarshaler interface and append append it to the array.

func (*Array) RawJSON added in v1.26.3

func (a *Array) RawJSON(val []byte) *Array

RawJSON adds already encoded JSON to the array.

func (*Array) Str added in v1.1.0

func (a *Array) Str(val string) *Array

Str append append the val as a string to the array.

func (*Array) Time added in v1.1.0

func (a *Array) Time(t time.Time) *Array

Time append append t formatted as string using zerolog.TimeFieldFormat.

func (*Array) Uint added in v1.1.0

func (a *Array) Uint(i uint) *Array

Uint append append i as a uint to the array.

func (*Array) Uint16 added in v1.1.0

func (a *Array) Uint16(i uint16) *Array

Uint16 append append i as a uint16 to the array.

func (*Array) Uint32 added in v1.1.0

func (a *Array) Uint32(i uint32) *Array

Uint32 append append i as a uint32 to the array.

func (*Array) Uint64 added in v1.1.0

func (a *Array) Uint64(i uint64) *Array

Uint64 append append i as a uint64 to the array.

func (*Array) Uint8 added in v1.1.0

func (a *Array) Uint8(i uint8) *Array

Uint8 append append i as a uint8 to the array.

type BasicSampler added in v1.3.0

type BasicSampler struct {
	N uint32
	// contains filtered or unexported fields
}

BasicSampler is a sampler that will send every Nth events, regardless of their level.

func (*BasicSampler) Sample added in v1.3.0

func (s *BasicSampler) Sample(lvl Level) bool

Sample implements the Sampler interface.

type BurstSampler added in v1.3.0

type BurstSampler struct {
	// Burst is the maximum number of event per period allowed before calling
	// NextSampler.
	Burst uint32
	// Period defines the burst period. If 0, NextSampler is always called.
	Period time.Duration
	// NextSampler is the sampler used after the burst is reached. If nil,
	// events are always rejected after the burst.
	NextSampler Sampler
	// contains filtered or unexported fields
}

BurstSampler lets Burst events pass per Period then pass the decision to NextSampler. If Sampler is not set, all subsequent events are rejected.

func (*BurstSampler) Sample added in v1.3.0

func (s *BurstSampler) Sample(lvl Level) bool

Sample implements the Sampler interface.

type ConsoleWriter added in v1.2.1

type ConsoleWriter struct {
	// Out is the output destination.
	Out io.Writer

	// NoColor disables the colorized output.
	NoColor bool

	// TimeFormat specifies the format for timestamp in output.
	TimeFormat string

	// PartsOrder defines the order of parts in output.
	PartsOrder []string

	// PartsExclude defines parts to not display in output.
	PartsExclude []string

	// FieldsExclude defines contextual fields to not display in output.
	FieldsExclude []string

	FormatTimestamp     Formatter
	FormatLevel         Formatter
	FormatCaller        Formatter
	FormatMessage       Formatter
	FormatFieldName     Formatter
	FormatFieldValue    Formatter
	FormatErrFieldName  Formatter
	FormatErrFieldValue Formatter

	FormatExtra func(map[string]interface{}, *bytes.Buffer) error
}

ConsoleWriter parses the JSON input and writes it in an (optionally) colorized, human-friendly format to Out.

Example
log := zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true})

log.Info().Str("foo", "bar").Msg("Hello World")
Output:

<nil> INF Hello World foo=bar
Example (CustomFormatters)
out := zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true}
out.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%-6s|", i)) }
out.FormatFieldName = func(i interface{}) string { return fmt.Sprintf("%s:", i) }
out.FormatFieldValue = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%s", i)) }
log := zerolog.New(out)

log.Info().Str("foo", "bar").Msg("Hello World")
Output:

<nil> INFO  | Hello World foo:BAR

func NewConsoleWriter added in v1.26.3

func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter

NewConsoleWriter creates and initializes a new ConsoleWriter.

Example
out := zerolog.NewConsoleWriter()
out.NoColor = true // For testing purposes only
log := zerolog.New(out)

log.Debug().Str("foo", "bar").Msg("Hello World")
Output:

<nil> DBG Hello World foo=bar
Example (CustomFormatters)
out := zerolog.NewConsoleWriter(
	func(w *zerolog.ConsoleWriter) {
		// Customize time format
		w.TimeFormat = time.RFC822
		// Customize level formatting
		w.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("[%-5s]", i)) }
	},
)
out.NoColor = true // For testing purposes only

log := zerolog.New(out)

log.Info().Str("foo", "bar").Msg("Hello World")
Output:

<nil> [INFO ] Hello World foo=bar

func (ConsoleWriter) Write added in v1.2.1

func (w ConsoleWriter) Write(p []byte) (n int, err error)

Write transforms the JSON input with formatters and appends to w.Out.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context configures a new sub-logger with contextual fields.

func (Context) AnErr

func (c Context) AnErr(key string, err error) Context

AnErr adds the field key with serialized err to the logger context.

func (Context) Array added in v1.1.0

func (c Context) Array(key string, arr LogArrayMarshaler) Context

Array adds the field key with an array to the event context. Use zerolog.Arr() to create the array or pass a type that implement the LogArrayMarshaler interface.

Example
log := zerolog.New(os.Stdout).With().
	Str("foo", "bar").
	Array("array", zerolog.Arr().
		Str("baz").
		Int(1),
	).Logger()

log.Log().Msg("hello world")
Output:

{"foo":"bar","array":["baz",1],"message":"hello world"}
Example (Object)
// Users implements zerolog.LogArrayMarshaler
u := Users{
	User{"John", 35, time.Time{}},
	User{"Bob", 55, time.Time{}},
}

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

log.Log().Msg("hello world")
Output:

{"foo":"bar","users":[{"name":"John","age":35,"created":"0001-01-01T00:00:00Z"},{"name":"Bob","age":55,"created":"0001-01-01T00:00:00Z"}],"message":"hello world"}

func (Context) Bool

func (c Context) Bool(key string, b bool) Context

Bool adds the field key with val as a bool to the logger context.

func (Context) Bools added in v1.0.1

func (c Context) Bools(key string, b []bool) Context

Bools adds the field key with val as a []bool to the logger context.

func (Context) Bytes added in v1.0.1

func (c Context) Bytes(key string, val []byte) Context

Bytes adds the field key with val as a []byte to the logger context.

func (Context) Caller added in v1.5.0

func (c Context) Caller() Context

Caller adds the file:line of the caller with the zerolog.CallerFieldName key.

func (Context) CallerWithSkipFrameCount added in v1.26.3

func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context

CallerWithSkipFrameCount adds the file:line of the caller with the zerolog.CallerFieldName key. The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger. If set to -1 the global CallerSkipFrameCount will be used.

func (Context) Dict

func (c Context) Dict(key string, dict *Event) Context

Dict adds the field key with the dict to the logger context.

Example
log := zerolog.New(os.Stdout).With().
	Str("foo", "bar").
	Dict("dict", zerolog.Dict().
		Str("bar", "baz").
		Int("n", 1),
	).Logger()

log.Log().Msg("hello world")
Output:

{"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}

func (Context) Dur

func (c Context) Dur(key string, d time.Duration) Context

Dur adds the fields key with d divided by unit and stored as a float.

Example
d := 10 * time.Second

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

log.Log().Msg("hello world")
Output:

{"foo":"bar","dur":10000,"message":"hello world"}

func (Context) Durs added in v1.0.1

func (c Context) Durs(key string, d []time.Duration) Context

Durs adds the fields key with d divided by unit and stored as a float.

Example
d := []time.Duration{
	10 * time.Second,
	20 * time.Second,
}

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

log.Log().Msg("hello world")
Output:

{"foo":"bar","durs":[10000,20000],"message":"hello world"}

func (Context) EmbedObject added in v1.7.0

func (c Context) EmbedObject(obj LogObjectMarshaler) Context

EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface.

Example
price := Price{val: 6449, prec: 2, unit: "$"}

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

log.Log().Msg("hello world")
Output:

{"foo":"bar","price":"$64.49","message":"hello world"}

func (Context) Err

func (c Context) Err(err error) Context

Err adds the field "error" with serialized err to the logger context.

func (Context) Errs added in v1.0.1

func (c Context) Errs(key string, errs []error) Context

Errs adds the field key with errs as an array of serialized errors to the logger context.

func (Context) Fields added in v1.0.1

func (c Context) Fields(fields interface{}) Context

Fields is a helper function to use a map or slice to set fields using type assertion. Only map[string]interface{} and []interface{} are accepted. []interface{} must alternate string keys and arbitrary values, and extraneous ones are ignored.

Example (Map)
fields := map[string]interface{}{
	"bar": "baz",
	"n":   1,
}

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

log.Log().Msg("hello world")
Output:

{"foo":"bar","bar":"baz","n":1,"message":"hello world"}
Example (Slice)
fields := []interface{}{
	"bar", "baz",
	"n", 1,
}

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

log.Log().Msg("hello world")
Output:

{"foo":"bar","bar":"baz","n":1,"message":"hello world"}

func (Context) Float32

func (c Context) Float32(key string, f float32) Context

Float32 adds the field key with f as a float32 to the logger context.

func (Context) Float64

func (c Context) Float64(key string, f float64) Context

Float64 adds the field key with f as a float64 to the logger context.

func (Context) Floats32 added in v1.0.1

func (c Context) Floats32(key string, f []float32) Context

Floats32 adds the field key with f as a []float32 to the logger context.

func (Context) Floats64 added in v1.0.1

func (c Context) Floats64(key string, f []float64) Context

Floats64 adds the field key with f as a []float64 to the logger context.

func (Context) Hex added in v1.6.0

func (c Context) Hex(key string, val []byte) Context

Hex adds the field key with val as a hex string to the logger context.

func (Context) IPAddr added in v1.7.0

func (c Context) IPAddr(key string, ip net.IP) Context

IPAddr adds IPv4 or IPv6 Address to the context

Example
hostIP := net.IP{192, 168, 0, 100}
log := zerolog.New(os.Stdout).With().
	IPAddr("HostIP", hostIP).
	Logger()

log.Log().Msg("hello world")
Output:

{"HostIP":"192.168.0.100","message":"hello world"}

func (Context) IPPrefix added in v1.7.0

func (c Context) IPPrefix(key string, pfx net.IPNet) Context

IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the context

Example
route := net.IPNet{IP: net.IP{192, 168, 0, 0}, Mask: net.CIDRMask(24, 32)}
log := zerolog.New(os.Stdout).With().
	IPPrefix("Route", route).
	Logger()

log.Log().Msg("hello world")
Output:

{"Route":"192.168.0.0/24","message":"hello world"}

func (Context) Int

func (c Context) Int(key string, i int) Context

Int adds the field key with i as a int to the logger context.

func (Context) Int16

func (c Context) Int16(key string, i int16) Context

Int16 adds the field key with i as a int16 to the logger context.

func (Context) Int32

func (c Context) Int32(key string, i int32) Context

Int32 adds the field key with i as a int32 to the logger context.

func (Context) Int64

func (c Context) Int64(key string, i int64) Context

Int64 adds the field key with i as a int64 to the logger context.

func (Context) Int8

func (c Context) Int8(key string, i int8) Context

Int8 adds the field key with i as a int8 to the logger context.

func (Context) Interface

func (c Context) Interface(key string, i interface{}) Context

Interface adds the field key with obj marshaled using reflection.

Example
obj := struct {
	Name string `json:"name"`
}{
	Name: "john",
}

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

log.Log().Msg("hello world")
Output:

{"foo":"bar","obj":{"name":"john"},"message":"hello world"}

func (Context) Ints added in v1.0.1

func (c Context) Ints(key string, i []int) Context

Ints adds the field key with i as a []int to the logger context.

func (Context) Ints16 added in v1.0.1

func (c Context) Ints16(key string, i []int16) Context

Ints16 adds the field key with i as a []int16 to the logger context.

func (Context) Ints32 added in v1.0.1

func (c Context) Ints32(key string, i []int32) Context

Ints32 adds the field key with i as a []int32 to the logger context.

func (Context) Ints64 added in v1.0.1

func (c Context) Ints64(key string, i []int64) Context

Ints64 adds the field key with i as a []int64 to the logger context.

func (Context) Ints8 added in v1.0.1

func (c Context) Ints8(key string, i []int8) Context

Ints8 adds the field key with i as a []int8 to the logger context.

func (Context) Logger

func (c Context) Logger() Logger

Logger returns the logger with the context previously set.

func (Context) MACAddr added in v1.7.0

func (c Context) MACAddr(key string, ha net.HardwareAddr) Context

MACAddr adds MAC address to the context

Example
mac := net.HardwareAddr{0x00, 0x14, 0x22, 0x01, 0x23, 0x45}
log := zerolog.New(os.Stdout).With().
	MACAddr("hostMAC", mac).
	Logger()

log.Log().Msg("hello world")
Output:

{"hostMAC":"00:14:22:01:23:45","message":"hello world"}

func (Context) Object added in v1.0.3

func (c Context) Object(key string, obj LogObjectMarshaler) Context

Object marshals an object that implement the LogObjectMarshaler interface.

Example
// User implements zerolog.LogObjectMarshaler
u := User{"John", 35, time.Time{}}

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

log.Log().Msg("hello world")
Output:

{"foo":"bar","user":{"name":"John","age":35,"created":"0001-01-01T00:00:00Z"},"message":"hello world"}

func (Context) RawJSON added in v1.5.0

func (c Context) RawJSON(key string, b []byte) Context

RawJSON adds already encoded JSON to context.

No sanity check is performed on b; it must not contain carriage returns and be valid JSON.

func (Context) Stack added in v1.26.3

func (c Context) Stack() Context

Stack enables stack trace printing for the error passed to Err().

func (Context) Str

func (c Context) Str(key, val string) Context

Str adds the field key with val as a string to the logger context.

func (Context) Stringer added in v1.26.3

func (c Context) Stringer(key string, val fmt.Stringer) Context

Stringer adds the field key with val.String() (or null if val is nil) to the logger context.

func (Context) Strs added in v1.0.1

func (c Context) Strs(key string, vals []string) Context

Strs adds the field key with val as a string to the logger context.

func (Context) Time

func (c Context) Time(key string, t time.Time) Context

Time adds the field key with t formated as string using zerolog.TimeFieldFormat.

func (Context) Times added in v1.0.1

func (c Context) Times(key string, t []time.Time) Context

Times adds the field key with t formated as string using zerolog.TimeFieldFormat.

func (Context) Timestamp

func (c Context) Timestamp() Context

Timestamp adds the current local time as UNIX timestamp to the logger context with the "time" key. To customize the key name, change zerolog.TimestampFieldName.

NOTE: It won't dedupe the "time" key if the *Context has one already.

func (Context) Uint

func (c Context) Uint(key string, i uint) Context

Uint adds the field key with i as a uint to the logger context.

func (Context) Uint16

func (c Context) Uint16(key string, i uint16) Context

Uint16 adds the field key with i as a uint16 to the logger context.

func (Context) Uint32

func (c Context) Uint32(key string, i uint32) Context

Uint32 adds the field key with i as a uint32 to the logger context.

func (Context) Uint64

func (c Context) Uint64(key string, i uint64) Context

Uint64 adds the field key with i as a uint64 to the logger context.

func (Context) Uint8

func (c Context) Uint8(key string, i uint8) Context

Uint8 adds the field key with i as a uint8 to the logger context.

func (Context) Uints added in v1.0.1

func (c Context) Uints(key string, i []uint) Context

Uints adds the field key with i as a []uint to the logger context.

func (Context) Uints16 added in v1.0.1

func (c Context) Uints16(key string, i []uint16) Context

Uints16 adds the field key with i as a []uint16 to the logger context.

func (Context) Uints32 added in v1.0.1

func (c Context) Uints32(key string, i []uint32) Context

Uints32 adds the field key with i as a []uint32 to the logger context.

func (Context) Uints64 added in v1.0.1

func (c Context) Uints64(key string, i []uint64) Context

Uints64 adds the field key with i as a []uint64 to the logger context.

func (Context) Uints8 added in v1.0.1

func (c Context) Uints8(key string, i []uint8) Context

Uints8 adds the field key with i as a []uint8 to the logger context.

type Event

type Event struct {
	// contains filtered or unexported fields
}

Event represents a log event. It is instanced by one of the level method of Logger and finalized by the Msg or Msgf method.

func Dict

func Dict() *Event

Dict creates an Event to be used with the *Event.Dict method. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the *Event.Dict method.

func (*Event) AnErr

func (e *Event) AnErr(key string, err error) *Event

AnErr adds the field key with serialized err to the *Event context. If err is nil, no field is added.

func (*Event) Array added in v1.1.0

func (e *Event) Array(key string, arr LogArrayMarshaler) *Event

Array adds the field key with an array to the event context. Use zerolog.Arr() to create the array or pass a type that implement the LogArrayMarshaler interface.

Example
log := zerolog.New(os.Stdout)

log.Log().
	Str("foo", "bar").
	Array("array", zerolog.Arr().
		Str("baz").
		Int(1).
		Dict(zerolog.Dict().
			Str("bar", "baz").
			Int("n", 1),
		),
	).
	Msg("hello world")
Output:

{"foo":"bar","array":["baz",1,{"bar":"baz","n":1}],"message":"hello world"}
Example (Object)
log := zerolog.New(os.Stdout)

// Users implements zerolog.LogArrayMarshaler
u := Users{
	User{"John", 35, time.Time{}},
	User{"Bob", 55, time.Time{}},
}

log.Log().
	Str("foo", "bar").
	Array("users", u).
	Msg("hello world")
Output:

{"foo":"bar","users":[{"name":"John","age":35,"created":"0001-01-01T00:00:00Z"},{"name":"Bob","age":55,"created":"0001-01-01T00:00:00Z"}],"message":"hello world"}

func (*Event) Bool

func (e *Event) Bool(key string, b bool) *Event

Bool adds the field key with val as a bool to the *Event context.

func (*Event) Bools added in v1.0.1

func (e *Event) Bools(key string, b []bool) *Event

Bools adds the field key with val as a []bool to the *Event context.

func (*Event) Bytes added in v1.0.1

func (e *Event) Bytes(key string, val []byte) *Event

Bytes adds the field key with val as a string to the *Event context.

Runes outside of normal ASCII ranges will be hex-encoded in the resulting JSON.

func (*Event) Caller added in v1.5.0

func (e *Event) Caller(skip ...int) *Event

Caller adds the file:line of the caller with the zerolog.CallerFieldName key. The argument skip is the number of stack frames to ascend Skip If not passed, use the global variable CallerSkipFrameCount

func (*Event) CallerSkipFrame added in v1.26.3

func (e *Event) CallerSkipFrame(skip int) *Event

CallerSkipFrame instructs any future Caller calls to skip the specified number of frames. This includes those added via hooks from the context.

func (*Event) Dict

func (e *Event) Dict(key string, dict *Event) *Event

Dict adds the field key with a dict to the event context. Use zerolog.Dict() to create the dictionary.

Example
log := zerolog.New(os.Stdout)

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

{"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}

func (*Event) Discard added in v1.26.3

func (e *Event) Discard() *Event

Discard disables the event so Msg(f) won't print it.

func (*Event) Dur

func (e *Event) Dur(key string, d time.Duration) *Event

Dur adds the field key with duration d stored as zerolog.DurationFieldUnit. If zerolog.DurationFieldInteger is true, durations are rendered as integer instead of float.

Example
d := 10 * time.Second

log := zerolog.New(os.Stdout)

log.Log().
	Str("foo", "bar").
	Dur("dur", d).
	Msg("hello world")
Output:

{"foo":"bar","dur":10000,"message":"hello world"}

func (*Event) Durs added in v1.0.1

func (e *Event) Durs(key string, d []time.Duration) *Event

Durs adds the field key with duration d stored as zerolog.DurationFieldUnit. If zerolog.DurationFieldInteger is true, durations are rendered as integer instead of float.

Example
d := []time.Duration{
	10 * time.Second,
	20 * time.Second,
}

log := zerolog.New(os.Stdout)

log.Log().
	Str("foo", "bar").
	Durs("durs", d).
	Msg("hello world")
Output:

{"foo":"bar","durs":[10000,20000],"message":"hello world"}

func (*Event) EmbedObject added in v1.7.0

func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event

EmbedObject marshals an object that implement the LogObjectMarshaler interface.

Example
log := zerolog.New(os.Stdout)

price := Price{val: 6449, prec: 2, unit: "$"}

log.Log().
	Str("foo", "bar").
	EmbedObject(price).
	Msg("hello world")
Output:

{"foo":"bar","price":"$64.49","message":"hello world"}

func (*Event) Enabled

func (e *Event) Enabled() bool

Enabled return false if the *Event is going to be filtered out by log level or sampling.

func (*Event) Err

func (e *Event) Err(err error) *Event

Err adds the field "error" with serialized err to the *Event context. If err is nil, no field is added.

To customize the key name, change zerolog.ErrorFieldName.

If Stack() has been called before and zerolog.ErrorStackMarshaler is defined, the err is passed to ErrorStackMarshaler and the result is appended to the zerolog.ErrorStackFieldName.

func (*Event) Errs added in v1.0.1

func (e *Event) Errs(key string, errs []error) *Event

Errs adds the field key with errs as an array of serialized errors to the *Event context.

func (*Event) Fields added in v1.0.1

func (e *Event) Fields(fields interface{}) *Event

Fields is a helper function to use a map or slice to set fields using type assertion. Only map[string]interface{} and []interface{} are accepted. []interface{} must alternate string keys and arbitrary values, and extraneous ones are ignored.

Example (Map)
fields := map[string]interface{}{
	"bar": "baz",
	"n":   1,
}

log := zerolog.New(os.Stdout)

log.Log().
	Str("foo", "bar").
	Fields(fields).
	Msg("hello world")
Output:

{"foo":"bar","bar":"baz","n":1,"message":"hello world"}
Example (Slice)
fields := []interface{}{
	"bar", "baz",
	"n", 1,
}

log := zerolog.New(os.Stdout)

log.Log().
	Str("foo", "bar").
	Fields(fields).
	Msg("hello world")
Output:

{"foo":"bar","bar":"baz","n":1,"message":"hello world"}

func (*Event) Float32

func (e *Event) Float32(key string, f float32) *Event

Float32 adds the field key with f as a float32 to the *Event context.

func (*Event) Float64

func (e *Event) Float64(key string, f float64) *Event

Float64 adds the field key with f as a float64 to the *Event context.

func (*Event) Floats32 added in v1.0.1

func (e *Event) Floats32(key string, f []float32) *Event

Floats32 adds the field key with f as a []float32 to the *Event context.

func (*Event) Floats64 added in v1.0.1

func (e *Event) Floats64(key string, f []float64) *Event

Floats64 adds the field key with f as a []float64 to the *Event context.

func (*Event) Func added in v1.26.3

func (e *Event) Func(f func(e *Event)) *Event

Func allows an anonymous func to run only if the event is enabled.

func (*Event) Hex added in v1.6.0

func (e *Event) Hex(key string, val []byte) *Event

Hex adds the field key with val as a hex string to the *Event context.

func (*Event) IPAddr added in v1.7.0

func (e *Event) IPAddr(key string, ip net.IP) *Event

IPAddr adds IPv4 or IPv6 Address to the event

func (*Event) IPPrefix added in v1.7.0

func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event

IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the event

func (*Event) Int

func (e *Event) Int(key string, i int) *Event

Int adds the field key with i as a int to the *Event context.

func (*Event) Int16

func (e *Event) Int16(key string, i int16) *Event

Int16 adds the field key with i as a int16 to the *Event context.

func (*Event) Int32

func (e *Event) Int32(key string, i int32) *Event

Int32 adds the field key with i as a int32 to the *Event context.

func (*Event) Int64

func (e *Event) Int64(key string, i int64) *Event

Int64 adds the field key with i as a int64 to the *Event context.

func (*Event) Int8

func (e *Event) Int8(key string, i int8) *Event

Int8 adds the field key with i as a int8 to the *Event context.

func (*Event) Interface

func (e *Event) Interface(key string, i interface{}) *Event

Interface adds the field key with i marshaled using reflection.

Example
log := zerolog.New(os.Stdout)

obj := struct {
	Name string `json:"name"`
}{
	Name: "john",
}

log.Log().
	Str("foo", "bar").
	Interface("obj", obj).
	Msg("hello world")
Output:

{"foo":"bar","obj":{"name":"john"},"message":"hello world"}

func (*Event) Ints added in v1.0.1

func (e *Event) Ints(key string, i []int) *Event

Ints adds the field key with i as a []int to the *Event context.

func (*Event) Ints16 added in v1.0.1

func (e *Event) Ints16(key string, i []int16) *Event

Ints16 adds the field key with i as a []int16 to the *Event context.

func (*Event) Ints32 added in v1.0.1

func (e *Event) Ints32(key string, i []int32) *Event

Ints32 adds the field key with i as a []int32 to the *Event context.

func (*Event) Ints64 added in v1.0.1

func (e *Event) Ints64(key string, i []int64) *Event

Ints64 adds the field key with i as a []int64 to the *Event context.

func (*Event) Ints8 added in v1.0.1

func (e *Event) Ints8(key string, i []int8) *Event

Ints8 adds the field key with i as a []int8 to the *Event context.

func (*Event) MACAddr added in v1.7.0

func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event

MACAddr adds MAC address to the event

func (*Event) Msg

func (e *Event) Msg(msg string)

Msg sends the *Event with msg added as the message field if not empty.

NOTICE: once this method is called, the *Event should be disposed. Calling Msg twice can have unexpected result.

func (*Event) MsgContext added in v1.26.3

func (e *Event) MsgContext(ctx context.Context, msg string)

MsgContext sends the *Event with ctx and msg added as the message field if not empty.

NOTICE: once this method is called, the *Event should be disposed. Calling Msg twice can have unexpected result.

func (*Event) MsgFunc added in v1.26.3

func (e *Event) MsgFunc(createMsg func() string)

func (*Event) Msgf

func (e *Event) Msgf(format string, v ...interface{})

Msgf sends the event with formatted msg added as the message field if not empty.

NOTICE: once this method is called, the *Event should be disposed. Calling Msgf twice can have unexpected result.

func (*Event) MsgfContext added in v1.26.3

func (e *Event) MsgfContext(ctx context.Context, format string, v ...interface{})

MsgfContext sends the event with ctx and formatted msg added as the message field if not empty.

NOTICE: once this method is called, the *Event should be disposed. Calling Msgf twice can have unexpected result.

func (*Event) Object added in v1.0.3

func (e *Event) Object(key string, obj LogObjectMarshaler) *Event

Object marshals an object that implement the LogObjectMarshaler interface.

Example
log := zerolog.New(os.Stdout)

// User implements zerolog.LogObjectMarshaler
u := User{"John", 35, time.Time{}}

log.Log().
	Str("foo", "bar").
	Object("user", u).
	Msg("hello world")
Output:

{"foo":"bar","user":{"name":"John","age":35,"created":"0001-01-01T00:00:00Z"},"message":"hello world"}

func (*Event) RawJSON added in v1.5.0

func (e *Event) RawJSON(key string, b []byte) *Event

RawJSON adds already encoded JSON to the log line under key.

No sanity check is performed on b; it must not contain carriage returns and be valid JSON.

func (*Event) Send added in v1.26.3

func (e *Event) Send()

Send is equivalent to calling Msg("").

NOTICE: once this method is called, the *Event should be disposed.

func (*Event) SendContext added in v1.26.3

func (e *Event) SendContext(ctx context.Context)

SendContext is equivalent to calling MsgContext("").

NOTICE: once this method is called, the *Event should be disposed.

func (*Event) Stack added in v1.26.3

func (e *Event) Stack() *Event

Stack enables stack trace printing for the error passed to Err().

ErrorStackMarshaler must be set for this method to do something.

func (*Event) Str

func (e *Event) Str(key, val string) *Event

Str adds the field key with val as a string to the *Event context.

func (*Event) Stringer added in v1.26.3

func (e *Event) Stringer(key string, val fmt.Stringer) *Event

Stringer adds the field key with val.String() (or null if val is nil) to the *Event context.

func (*Event) Stringers added in v1.26.3

func (e *Event) Stringers(key string, vals []fmt.Stringer) *Event

Stringers adds the field key with vals where each individual val is used as val.String() (or null if val is empty) to the *Event context.

func (*Event) Strs added in v1.0.1

func (e *Event) Strs(key string, vals []string) *Event

Strs adds the field key with vals as a []string to the *Event context.

func (*Event) Time

func (e *Event) Time(key string, t time.Time) *Event

Time adds the field key with t formatted as string using zerolog.TimeFieldFormat.

func (*Event) TimeDiff

func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event

TimeDiff adds the field key with positive duration between time t and start. If time t is not greater than start, duration will be 0. Duration format follows the same principle as Dur().

func (*Event) Times added in v1.0.1

func (e *Event) Times(key string, t []time.Time) *Event

Times adds the field key with t formatted as string using zerolog.TimeFieldFormat.

func (*Event) Timestamp

func (e *Event) Timestamp() *Event

Timestamp adds the current local time as UNIX timestamp to the *Event context with the "time" key. To customize the key name, change zerolog.TimestampFieldName.

NOTE: It won't dedupe the "time" key if the *Event (or *Context) has one already.

func (*Event) Type added in v1.28.0

func (e *Event) Type(key string, val interface{}) *Event

Type adds the field key with val's type using reflection.

func (*Event) Uint

func (e *Event) Uint(key string, i uint) *Event

Uint adds the field key with i as a uint to the *Event context.

func (*Event) Uint16

func (e *Event) Uint16(key string, i uint16) *Event

Uint16 adds the field key with i as a uint16 to the *Event context.

func (*Event) Uint32

func (e *Event) Uint32(key string, i uint32) *Event

Uint32 adds the field key with i as a uint32 to the *Event context.

func (*Event) Uint64

func (e *Event) Uint64(key string, i uint64) *Event

Uint64 adds the field key with i as a uint64 to the *Event context.

func (*Event) Uint8

func (e *Event) Uint8(key string, i uint8) *Event

Uint8 adds the field key with i as a uint8 to the *Event context.

func (*Event) Uints added in v1.0.1

func (e *Event) Uints(key string, i []uint) *Event

Uints adds the field key with i as a []int to the *Event context.

func (*Event) Uints16 added in v1.0.1

func (e *Event) Uints16(key string, i []uint16) *Event

Uints16 adds the field key with i as a []int16 to the *Event context.

func (*Event) Uints32 added in v1.0.1

func (e *Event) Uints32(key string, i []uint32) *Event

Uints32 adds the field key with i as a []int32 to the *Event context.

func (*Event) Uints64 added in v1.0.1

func (e *Event) Uints64(key string, i []uint64) *Event

Uints64 adds the field key with i as a []int64 to the *Event context.

func (*Event) Uints8 added in v1.0.1

func (e *Event) Uints8(key string, i []uint8) *Event

Uints8 adds the field key with i as a []int8 to the *Event context.

type Formatter added in v1.26.3

type Formatter func(interface{}) string

Formatter transforms the input into a formatted string.

type Hook added in v1.4.0

type Hook interface {
	// Run runs the hook with the event.
	Run(e *Event, ctx context.Context, level Level, message string)
}

Hook defines an interface to a log hook.

type HookFunc added in v1.26.3

type HookFunc func(e *Event, ctx context.Context, level Level, message string)

HookFunc is an adaptor to allow the use of an ordinary function as a Hook.

func (HookFunc) Run added in v1.26.3

func (h HookFunc) Run(e *Event, ctx context.Context, level Level, message string)

Run implements the Hook interface.

type Level

type Level int8

Level defines log levels.

const (
	// DebugLevel defines debug log level.
	DebugLevel Level = iota
	// InfoLevel defines info log level.
	InfoLevel
	// WarnLevel defines warn log level.
	WarnLevel
	// ErrorLevel defines error log level.
	ErrorLevel
	// FatalLevel defines fatal log level.
	FatalLevel
	// PanicLevel defines panic log level.
	PanicLevel
	// NoLevel defines an absent log level.
	NoLevel
	// Disabled disables the logger.
	Disabled

	// TraceLevel defines trace log level.
	TraceLevel Level = -1
)

func GlobalLevel added in v1.7.0

func GlobalLevel() Level

GlobalLevel returns the current global log level

func ParseLevel added in v1.7.0

func ParseLevel(levelStr string) (Level, error)

ParseLevel converts a level string into a zerolog Level value. returns an error if the input string does not match known values.

func (Level) MarshalText added in v1.27.0

func (l Level) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler to allow for easy writing into toml/yaml/json formats

func (Level) String

func (l Level) String() string

func (*Level) UnmarshalText added in v1.27.0

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler to allow for easy reading from toml/yaml/json formats

type LevelHook added in v1.4.0

type LevelHook struct {
	NoLevelHook, TraceHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook
}

LevelHook applies a different hook for each level.

func NewLevelHook added in v1.4.0

func NewLevelHook() LevelHook

NewLevelHook returns a new LevelHook.

func (LevelHook) Run added in v1.4.0

func (h LevelHook) Run(e *Event, ctx context.Context, level Level, message string)

Run implements the Hook interface.

type LevelSampler added in v1.3.0

type LevelSampler struct {
	TraceSampler, DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler
}

LevelSampler applies a different sampler for each level.

func (LevelSampler) Sample added in v1.3.0

func (s LevelSampler) Sample(lvl Level) bool

type LevelWriter

type LevelWriter interface {
	io.Writer
	WriteLevel(level Level, p []byte) (n int, err error)
}

LevelWriter defines as interface a writer may implement in order to receive level information with payload.

func MultiLevelWriter

func MultiLevelWriter(writers ...io.Writer) LevelWriter

MultiLevelWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command. If some writers implement LevelWriter, their WriteLevel method will be used instead of Write.

func SyslogCEEWriter added in v1.26.3

func SyslogCEEWriter(w SyslogWriter) LevelWriter

SyslogCEEWriter wraps a SyslogWriter with a SyslogLevelWriter that adds a MITRE CEE prefix for JSON syslog entries, compatible with rsyslog and syslog-ng JSON logging support. See https://www.rsyslog.com/json-elasticsearch/

func SyslogLevelWriter

func SyslogLevelWriter(w SyslogWriter) LevelWriter

SyslogLevelWriter wraps a SyslogWriter and call the right syslog level method matching the zerolog level.

type LogArrayMarshaler added in v1.1.0

type LogArrayMarshaler interface {
	MarshalZerologArray(a *Array)
}

LogArrayMarshaler provides a strongly-typed and encoding-agnostic interface to be implemented by types used with Event/Context's Array methods.

type LogObjectMarshaler added in v1.0.3

type LogObjectMarshaler interface {
	MarshalZerologObject(e *Event)
}

LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface to be implemented by types used with Event/Context's Object methods.

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

A Logger represents an active logging object that generates lines of JSON output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. There is no guarantee on access serialization to the Writer. If your Writer is not thread safe, you may consider a sync wrapper.

func Ctx

func Ctx(ctx context.Context) *Logger

Ctx returns the Logger associated with the ctx. If no logger is associated, DefaultContextLogger is returned, unless DefaultContextLogger is nil, in which case a disabled logger is returned.

func New

func New(w io.Writer) Logger

New creates a root logger with given output writer. If the output writer implements the LevelWriter interface, the WriteLevel method will be called instead of the Write one.

Each logging operation makes a single call to the Writer's Write method. There is no guarantee on access serialization to the Writer. If your Writer is not thread safe, you may consider using sync wrapper.

Example
log := zerolog.New(os.Stdout)

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

{"level":"info","message":"hello world"}

func Nop

func Nop() Logger

Nop returns a disabled logger for which all operation are no-op.

func (*Logger) Debug

func (l *Logger) Debug() *Event

Debug starts a new message with debug level.

You must call Msg on the returned event in order to send the event.

Example
log := zerolog.New(os.Stdout)

log.Debug().
	Str("foo", "bar").
	Int("n", 123).
	Msg("hello world")
Output:

{"level":"debug","foo":"bar","n":123,"message":"hello world"}

func (*Logger) Err added in v1.26.3

func (l *Logger) Err(err error) *Event

Err starts a new message with error level with err as a field if not nil or with info level if err is nil.

You must call Msg on the returned event in order to send the event.

func (*Logger) Error

func (l *Logger) Error() *Event

Error starts a new message with error level.

You must call Msg on the returned event in order to send the event.

Example
log := zerolog.New(os.Stdout)

log.Error().
	Err(errors.New("some error")).
	Msg("error doing something")
Output:

{"level":"error","error":"some error","message":"error doing something"}

func (*Logger) Fatal

func (l *Logger) Fatal() *Event

Fatal starts a new message with fatal level. The os.Exit(1) function is called by the Msg method, which terminates the program immediately.

You must call Msg on the returned event in order to send the event.

func (Logger) GetLevel added in v1.26.3

func (l Logger) GetLevel() Level

GetLevel returns the current Level of l.

func (Logger) Hook added in v1.4.0

func (l Logger) Hook(h Hook) Logger

Hook returns a logger with the h Hook.

Example
var levelNameHook LevelNameHook
var messageHook MessageHook = "The message"

log := zerolog.New(os.Stdout).Hook(levelNameHook).Hook(messageHook)

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

{"level":"info","level_name":"info","the_message":"hello world","message":"hello world"}

func (*Logger) Info

func (l *Logger) Info() *Event

Info starts a new message with info level.

You must call Msg on the returned event in order to send the event.

Example
log := zerolog.New(os.Stdout)

log.Info().
	Str("foo", "bar").
	Int("n", 123).
	Msg("hello world")
Output:

{"level":"info","foo":"bar","n":123,"message":"hello world"}

func (Logger) Level

func (l Logger) Level(lvl Level) Logger

Level creates a child logger with the minimum accepted level set to level.

Example
log := zerolog.New(os.Stdout).Level(zerolog.WarnLevel)

log.Info().Msg("filtered out message")
log.Error().Msg("kept message")
Output:

{"level":"error","message":"kept message"}

func (*Logger) Log

func (l *Logger) Log() *Event

Log starts a new message with no level. Setting GlobalLevel to Disabled will still disable events produced by this method.

You must call Msg on the returned event in order to send the event.

Example
log := zerolog.New(os.Stdout)

log.Log().
	Str("foo", "bar").
	Str("bar", "baz").
	Msg("")
Output:

{"foo":"bar","bar":"baz"}

func (Logger) Output added in v1.2.0

func (l Logger) Output(w io.Writer) Logger

Output duplicates the current logger and sets w as its output.

func (*Logger) Panic

func (l *Logger) Panic() *Event

Panic starts a new message with panic level. The panic() function is called by the Msg method, which stops the ordinary flow of a goroutine.

You must call Msg on the returned event in order to send the event.

func (*Logger) Print added in v1.3.0

func (l *Logger) Print(v ...interface{})

Print sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Print.

Example
log := zerolog.New(os.Stdout)

log.Print("hello world")
Output:

{"level":"debug","message":"hello world"}

func (*Logger) Printf added in v1.3.0

func (l *Logger) Printf(format string, v ...interface{})

Printf sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Printf.

Example
log := zerolog.New(os.Stdout)

log.Printf("hello %s", "world")
Output:

{"level":"debug","message":"hello world"}

func (Logger) Sample

func (l Logger) Sample(s Sampler) Logger

Sample returns a logger with the s sampler.

Example
log := zerolog.New(os.Stdout).Sample(&zerolog.BasicSampler{N: 2})

log.Info().Msg("message 1")
log.Info().Msg("message 2")
log.Info().Msg("message 3")
log.Info().Msg("message 4")
Output:

{"level":"info","message":"message 1"}
{"level":"info","message":"message 3"}

func (*Logger) Trace added in v1.26.3

func (l *Logger) Trace() *Event

Trace starts a new message with trace level.

You must call Msg on the returned event in order to send the event.

Example
log := zerolog.New(os.Stdout)

log.Trace().
	Str("foo", "bar").
	Int("n", 123).
	Msg("hello world")
Output:

{"level":"trace","foo":"bar","n":123,"message":"hello world"}

func (*Logger) UpdateContext added in v1.3.0

func (l *Logger) UpdateContext(update func(c Context) Context)

UpdateContext updates the internal logger's context.

Use this method with caution. If unsure, prefer the With method.

func (*Logger) Warn

func (l *Logger) Warn() *Event

Warn starts a new message with warn level.

You must call Msg on the returned event in order to send the event.

Example
log := zerolog.New(os.Stdout)

log.Warn().
	Str("foo", "bar").
	Msg("a warning message")
Output:

{"level":"warn","foo":"bar","message":"a warning message"}

func (Logger) With

func (l Logger) With() Context

With creates a child logger with the field added to its context.

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

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

{"level":"info","foo":"bar","message":"hello world"}

func (Logger) WithContext

func (l Logger) WithContext(ctx context.Context) context.Context

WithContext returns a copy of ctx with the receiver attached. The Logger attached to the provided Context (if any) will not be effected. If the receiver's log level is Disabled it will only be attached to the returned Context if the provided Context has a previously attached Logger. If the provided Context has no attached Logger, a Disabled Logger will not be attached.

Note: to modify the existing Logger attached to a Context (instead of replacing it in a new Context), use UpdateContext with the following notation:

ctx := r.Context()
l := zerolog.Ctx(ctx)
l.UpdateContext(func(c Context) Context {
    return c.Str("bar", "baz")
})

func (*Logger) WithLevel added in v1.0.1

func (l *Logger) WithLevel(level Level) *Event

WithLevel starts a new message with level. Unlike Fatal and Panic methods, WithLevel does not terminate the program or stop the ordinary flow of a goroutine when used with their respective levels.

You must call Msg on the returned event in order to send the event.

Example
log := zerolog.New(os.Stdout)

log.WithLevel(zerolog.InfoLevel).
	Msg("hello world")
Output:

{"level":"info","message":"hello world"}

func (Logger) Write

func (l Logger) Write(p []byte) (n int, err error)

Write implements the io.Writer interface. This is useful to set as a writer for the standard library log.

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

type RandomSampler added in v1.3.0

type RandomSampler uint32

RandomSampler use a PRNG to randomly sample an event out of N events, regardless of their level.

func (RandomSampler) Sample added in v1.3.0

func (s RandomSampler) Sample(lvl Level) bool

Sample implements the Sampler interface.

type Sampler added in v1.3.0

type Sampler interface {
	// Sample returns true if the event should be part of the sample, false if
	// the event should be dropped.
	Sample(lvl Level) bool
}

Sampler defines an interface to a log sampler.

type SyslogWriter

type SyslogWriter interface {
	io.Writer
	Debug(m string) error
	Info(m string) error
	Warning(m string) error
	Err(m string) error
	Emerg(m string) error
	Crit(m string) error
}

SyslogWriter is an interface matching a syslog.Writer struct.

type TestWriter added in v1.26.3

type TestWriter struct {
	T TestingLog

	// Frame skips caller frames to capture the original file and line numbers.
	Frame int
}

TestWriter is a writer that writes to testing.TB.

func NewTestWriter added in v1.26.3

func NewTestWriter(t TestingLog) TestWriter

NewTestWriter creates a writer that logs to the testing.TB.

func (TestWriter) Write added in v1.26.3

func (t TestWriter) Write(p []byte) (n int, err error)

Write to testing.TB.

type TestingLog added in v1.26.3

type TestingLog interface {
	Log(args ...interface{})
	Logf(format string, args ...interface{})
	Helper()
}

TestingLog is the logging interface of testing.TB.

Directories

Path Synopsis
cmd
Package diode provides a thread-safe, lock-free, non-blocking io.Writer wrapper.
Package diode provides a thread-safe, lock-free, non-blocking io.Writer wrapper.
Package hlog provides a set of http.Handler helpers for zerolog.
Package hlog provides a set of http.Handler helpers for zerolog.
internal/mutil
Package mutil contains various functions that are helpful when writing http middleware.
Package mutil contains various functions that are helpful when writing http middleware.
internal
cbor
Package cbor provides primitives for storing different data in the CBOR (binary) format.
Package cbor provides primitives for storing different data in the CBOR (binary) format.
Package log provides a global logger for zerolog.
Package log provides a global logger for zerolog.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL