Root

github.com/rs/zerolog

import "github.com/rs/zerolog"

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

A global Logger can be used for simple logging:

import "github.com/rs/zerolog/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/rs/zerolog/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, 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

Field duplication:

There is no field deduplication out-of-the-box. Using the same key multiple times creates a new key in the 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.

Concurrency safety:

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

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

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

Constants

Source: globals.go:14

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"

	// DurationFormatFloat defines a format for Duration fields that makes duration fields to be
	// serialized as floating point numbers.
	DurationFormatFloat = "float"
	// DurationFormatInt defines a format for Duration fields that makes duration fields to be
	// serialized as integers.
	DurationFormatInt = "int"
	// DurationFormatString defines a format for Duration fields that makes duration fields to be
	// serialized as string.
	DurationFormatString = "string"
)

Source: log.go:131

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
)

Variables

Source: globals.go:41

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" with disabled HTML escaping
	InterfaceMarshalFunc = func(v interface{}) ([]byte, error) {
		var buf bytes.Buffer
		encoder := json.NewEncoder(&buf)
		encoder.SetEscapeHTML(false)
		err := encoder.Encode(v)
		if err != nil {
			return nil, err
		}
		b := buf.Bytes()
		if len(b) > 0 {

			return b[:len(b)-1], nil
		}
		return b, nil
	}

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

	// DurationFieldFormat defines the format of the Duration field type.
	DurationFieldFormat = DurationFormatFloat

	// 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.
	// Deprecated: use DurationFieldFormat with DurationFormatInt instead.
	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)

	// FatalExitFunc is called by log.Fatal() instead of os.Exit(1). If not set,
	// os.Exit(1) is called.
	FatalExitFunc func()

	// DefaultContextLogger is returned from Ctx() if there is no logger associated
	// with the context.
	DefaultContextLogger *Logger

	// LevelColors are used by ConsoleWriter's consoleDefaultFormatLevel to color
	// log levels.
	LevelColors = map[Level]int{
		TraceLevel: colorBlue,
		DebugLevel: 0,
		InfoLevel:  colorGreen,
		WarnLevel:  colorYellow,
		ErrorLevel: colorRed,
		FatalLevel: colorRed,
		PanicLevel: colorRed,
	}

	// FormattedLevels are used by ConsoleWriter's consoleDefaultFormatLevel
	// for a short level name.
	FormattedLevels = map[Level]string{
		TraceLevel: "TRC",
		DebugLevel: "DBG",
		InfoLevel:  "INF",
		WarnLevel:  "WRN",
		ErrorLevel: "ERR",
		FatalLevel: "FTL",
		PanicLevel: "PNC",
	}

	// TriggerLevelWriterBufferReuseLimit is a limit in bytes that a buffer is dropped
	// from the TriggerLevelWriter buffer pool if the buffer grows above the limit.
	TriggerLevelWriterBufferReuseLimit = 64 * 1024

	// FloatingPointPrecision, if set to a value other than -1, controls the number
	// of digits when formatting float numbers in JSON. See strconv.FormatFloat for
	// more details.
	FloatingPointPrecision = -1
)

Source: sampler.go:11

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 Arr() *Array

Source: array.go:50

Arr creates an array to be added to an Event or Context. WARNING: This function is deprecated because it does not preserve the stack, hooks, and context from the parent event. Deprecated: Use Event.CreateArray or Context.CreateArray instead.

func AsLogObjectMarshalers[T LogObjectMarshaler](objs []T) []LogObjectMarshaler

Source: globals_118.go:10

func AsStringers[T fmt.Stringer](objs []T) []fmt.Stringer

Source: globals_118.go:21

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

Source: writer.go:184

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

func Ctx(ctx context.Context) *Logger

Source: ctx.go:44

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 Dict() *Event

Source: event.go:208

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. NOTE: This function is deprecated because it does not preserve the stack, hooks, and context from the parent event. Deprecated: Use Event.CreateDict instead.

func DisableSampling(v bool)

Source: globals.go:198

DisableSampling will disable sampling in all Loggers if true.

func GlobalLevel() Level

Source: globals.go:193

GlobalLevel returns the current global log level

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

Source: writer.go:127

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 New(w io.Writer) Logger

Source: log.go:247

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 NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter

Source: console.go:102

NewConsoleWriter creates and initializes a new ConsoleWriter.

Example
{
	out := zerolog.NewConsoleWriter()
	out.NoColor = true
	log := zerolog.New(out)

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

}

Output:

<nil> DBG Hello World foo=bar

func NewLevelHook() LevelHook

Source: hook.go:62

NewLevelHook returns a new LevelHook.

func NewSlogHandler(logger Logger) *SlogHandler

Source: slog.go:21

NewSlogHandler creates a new slog.Handler that writes log records to the given zerolog.Logger. The handler maps slog levels to zerolog levels and converts slog attributes to zerolog fields.

func NewTestWriter(t TestingLog) TestWriter

Source: writer.go:155

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

func Nop() Logger

Source: log.go:259

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

func ParseLevel(levelStr string) (Level, error)

Source: log.go:178

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

func SetGlobalLevel(l Level)

Source: globals.go:188

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(w io.Writer) io.Writer

Source: writer.go:48

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.

func SyslogCEEWriter(w SyslogWriter) LevelWriter

Source: syslog.go:40

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(w SyslogWriter) LevelWriter

Source: syslog.go:32

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

Types

type Array

Source: array.go:20

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

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

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

Source: array.go:148

Bool appends the val as a bool to the array.

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

Source: array.go:89

Bytes appends the val as a string to the array.

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

Source: array.go:265

Dict adds the dict Event to the array

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

Source: array.go:232

Dur appends d to the array.

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

Source: array.go:107

Err serializes and appends the err to the array.

func (a *Array) Errs(errs []error) *Array

Source: array.go:127

Errs serializes and appends errors to the array.

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

Source: array.go:214

Float32 appends f as a float32 to the array.

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

Source: array.go:220

Float64 appends f as a float64 to the array.

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

Source: array.go:95

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

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

Source: array.go:247

IPAddr adds a net.IP IPv4 or IPv6 address to the array

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

Source: array.go:253

IPPrefix adds a net.IPNet IPv4 or IPv6 Prefix (IP + mask) to the array

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

Source: array.go:154

Int appends i as a int to the array.

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

Source: array.go:166

Int16 appends i as a int16 to the array.

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

Source: array.go:172

Int32 appends i as a int32 to the array.

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

Source: array.go:178

Int64 appends i as a int64 to the array.

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

Source: array.go:160

Int8 appends i as a int8 to the array.

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

Source: array.go:238

Interface appends i marshaled using reflection.

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

Source: array.go:259

MACAddr adds a net.HardwareAddr MAC (Ethernet) address to the array

func (*Array) MarshalZerologArray(*Array)

Source: array.go:61

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

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

Source: array.go:77

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

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

Source: array.go:101

RawJSON adds already encoded JSON to the array.

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

Source: array.go:83

Str appends the val as a string to the array.

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

Source: array.go:226

Time appends t formatted as string using zerolog.TimeFieldFormat.

func (a *Array) Type(val interface{}) *Array

Source: array.go:273

Type adds the val's type using reflection to the array.

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

Source: array.go:184

Uint appends i as a uint to the array.

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

Source: array.go:196

Uint16 appends i as a uint16 to the array.

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

Source: array.go:202

Uint32 appends i as a uint32 to the array.

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

Source: array.go:208

Uint64 appends i as a uint64 to the array.

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

Source: array.go:190

Uint8 appends i as a uint8 to the array.

type BasicSampler

Source: sampler.go:39

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

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

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

Source: sampler.go:45

Sample implements the Sampler interface.

type BurstSampler

Source: sampler.go:59

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

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
}
Fields
  • Burst uint32

    Burst is the maximum number of event per period allowed before calling NextSampler.

  • Period time.Duration

    Period defines the burst period. If 0, NextSampler is always called.

  • NextSampler Sampler

    NextSampler is the sampler used after the burst is reached. If nil, events are always rejected after the burst.

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

Source: sampler.go:74

Sample implements the Sampler interface.

type ConsoleWriter

Source: console.go:56

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

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

	// TimeLocation tells ConsoleWriter’s default FormatTimestamp
	// how to localize the time.
	TimeLocation *time.Location

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

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

	// FieldsOrder defines the order of contextual fields in output.
	FieldsOrder []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
	// If this is configured it is used for "part" values and
	// has precedence on FormatFieldValue
	FormatPartValueByName FormatterByFieldName

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

	FormatPrepare func(map[string]interface{}) error
	// contains filtered or unexported fields
}
Fields
  • Out io.Writer

    Out is the output destination.

  • NoColor bool

    NoColor disables the colorized output.

  • TimeFormat string

    TimeFormat specifies the format for timestamp in output.

  • TimeLocation *time.Location

    TimeLocation tells ConsoleWriter’s default FormatTimestamp how to localize the time.

  • PartsOrder []string

    PartsOrder defines the order of parts in output.

  • PartsExclude []string

    PartsExclude defines parts to not display in output.

  • FieldsOrder []string

    FieldsOrder defines the order of contextual fields in output.

  • FieldsExclude []string

    FieldsExclude defines contextual fields to not display in output.

  • FormatTimestamp Formatter
  • FormatLevel Formatter
  • FormatCaller Formatter
  • FormatMessage Formatter
  • FormatFieldName Formatter
  • FormatFieldValue Formatter
  • FormatErrFieldName Formatter
  • FormatErrFieldValue Formatter
  • FormatPartValueByName FormatterByFieldName

    If this is configured it is used for "part" values and has precedence on FormatFieldValue

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

func (w ConsoleWriter) Close() error

Source: console.go:178

Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.

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

Source: console.go:122

Write transforms the JSON input with formatters and appends to w.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

type Context

Source: context.go:12

Context configures a new sub-logger with contextual fields.

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

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

Source: context.go:183

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

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

Source: context.go:451

Any is a wrapper around Context.Interface.

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

Source: context.go:60

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

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

	logger := ctx.Array("array", ctx.CreateArray().
		Str("baz").
		Int(1),
	).Logger()

	logger.Log().Msg("hello world")

}

Output:

{"foo":"bar","array":["baz",1],"message":"hello world"}

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

Source: context.go:238

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

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

Source: context.go:244

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

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

Source: context.go:161

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

func (c Context) Caller() Context

Source: context.go:488

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

func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context

Source: context.go:496

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 (c Context) CreateArray() *Array

Source: context.go:49

CreateArray creates an Array to be used with the Context.Array method. It preserves the stack, hooks, and context from the logger. Call usual field methods like Str, Int etc to add elements to this array and give it as argument the Context.Array method.

func (c Context) CreateDict() *Event

Source: context.go:41

CreateDict creates an Event to be used with the Context.Dict method. It preserves the stack, hooks, and context from the logger. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the Context.Dict method.

func (c Context) Ctx(ctx context.Context) Context

Source: context.go:232

Ctx adds the context.Context to the logger context. The context.Context is not rendered in the error message, but is made available for hooks to use. A typical use case is to extract tracing information from the context.Context.

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

Source: context.go:30

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

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

	logger := ctx.Dict("dict", ctx.CreateDict().
		Str("bar", "baz").
		Int("n", 1),
	).Logger()

	logger.Log().Msg("hello world")

}

Output:

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

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

Source: context.go:424

Dur adds the field 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 (c Context) Durs(key string, d []time.Duration) Context

Source: context.go:430

Durs adds the field 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 (c Context) EmbedObject(obj LogObjectMarshaler) Context

Source: context.go:102

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 (c Context) Err(err error) Context

Source: context.go:209

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

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

Source: context.go:203

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

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

Source: context.go:24

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.

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

Source: context.go:370

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

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

Source: context.go:382

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

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

Source: context.go:376

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

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

Source: context.go:388

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

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

Source: context.go:167

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

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

Source: context.go:508

IPAddr adds the field key with ip as a net.IP 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 (c Context) IPAddrs(key string, ip []net.IP) Context

Source: context.go:514

IPAddrs adds the field key with ip as a []net.IP array of IPv4 or IPv6 Address to the context

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

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

}

Output:

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

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

Source: context.go:520

IPPrefix adds the field key with pfx as a []net.IPNet 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 (c Context) IPPrefixes(key string, pfx []net.IPNet) Context

Source: context.go:526

IPPrefix adds the field key with pfx as a []net.IPNet array of 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().
		IPPrefixes("Route", []net.IPNet{route}).
		Logger()

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

}

Output:

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

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

Source: context.go:250

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

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

Source: context.go:274

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

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

Source: context.go:286

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

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

Source: context.go:298

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

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

Source: context.go:262

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

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

Source: context.go:436

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 (c Context) Ints(key string, i []int) Context

Source: context.go:256

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

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

Source: context.go:280

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

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

Source: context.go:292

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

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

Source: context.go:304

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

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

Source: context.go:268

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

func (c Context) Logger() Logger

Source: context.go:17

Logger returns the logger with the context previously set.

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

Source: context.go:532

MACAddr adds the field key with ha as a net.HardwareAddr 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 (c Context) Object(key string, obj LogObjectMarshaler) Context

Source: context.go:73

Object marshals an object that implement the LogObjectMarshaler interface.

Example
{

	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 (c Context) Objects(key string, objs []LogObjectMarshaler) Context

Source: context.go:85

Objects adds the field key with objs to the logger context as an array of objects that implement the LogObjectMarshaler interface.

This is the array version that accepts a slice of LogObjectMarshaler objects.

Example
{

	u := User{"John", 35, time.Time{}}
	u2 := User{"Bono", 54, time.Time{}}

	log := zerolog.New(os.Stdout).With().
		Str("foo", "bar").
		Objects("users", []zerolog.LogObjectMarshaler{u, u2}).
		Logger()

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

}

Output:

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

func (c Context) ObjectsV(key string, objs ...LogObjectMarshaler) Context

Source: context.go:97

ObjectsV adds the field key with objs to the logger context as an array of objects that implement the LogObjectMarshaler interface.

This is a variadic version that accepts a list of individual LogObjectMarshaler objects.

Example
{

	u := User{"John", 35, time.Time{}}
	u2 := User{"Bono", 54, time.Time{}}

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

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

}

Output:

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

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

Source: context.go:176

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 (c Context) Reset() Context

Source: context.go:456

Reset removes all the context fields.

func (c Context) Stack() Context

Source: context.go:502

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

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

Source: context.go:111

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

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

Source: context.go:132

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

func (c Context) Stringers(key string, vals []fmt.Stringer) Context

Source: context.go:146

Stringers adds the field key with vals to the logger context where each individual val is added by calling val.String().

This is the array version that accepts a slice of fmt.Stringer values.

func (c Context) StringersV(key string, vals ...fmt.Stringer) Context

Source: context.go:156

StringersV adds the field key with vals to the logger context where each individual val is added by calling val.String().

This is a variadic version that accepts a list of individual fmt.Stringer values.

Example
{

	a := net.IPv4bcast
	b := net.IPv4allrouter

	log := zerolog.New(os.Stdout).With().
		StringersV("ips", a, b).
		Logger()

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

}

Output:

{"ips":["255.255.255.255","224.0.0.2"],"message":"hello world"}

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

Source: context.go:119

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

This is the array version that accepts a slice of string values.

func (c Context) StrsV(key string, vals ...string) Context

Source: context.go:127

StrsV adds the field key with vals as a []string to the logger context.

This is a variadic version that accepts a list of individual strings.

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

Source: context.go:412

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

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

Source: context.go:418

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

Example
{
	t1 := time.Time{}
	t2 := t1.Add(time.Second * 10)
	t := []time.Time{t1, t2}

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

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

}

Output:

{"foo":"bar","times":["0001-01-01T00:00:00Z","0001-01-01T00:00:10Z"],"message":"hello world"}

func (c Context) Timestamp() Context

Source: context.go:406

Timestamp adds the current local time to the logger context with the "time" key, formatted using zerolog.TimeFieldFormat. To customize the key name, change zerolog.TimestampFieldName. To customize the time format, change zerolog.TimeFieldFormat.

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

func (c Context) Type(key string, val interface{}) Context

Source: context.go:445

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

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

Source: context.go:310

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

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

Source: context.go:334

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

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

Source: context.go:346

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

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

Source: context.go:358

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

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

Source: context.go:322

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

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

Source: context.go:316

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

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

Source: context.go:340

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

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

Source: context.go:352

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

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

Source: context.go:364

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

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

Source: context.go:328

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

type Event

Source: event.go:23

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

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

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

Source: event.go:422

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

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

Source: event.go:820

Any is a wrapper around Event.Interface.

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

Source: event.go:229

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

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

	e := log.Log().
		Str("foo", "bar")

	e.Array("array", e.CreateArray().
		Str("baz").
		Int(1).
		Dict(e.CreateDict().
			Str("bar", "baz").
			Int("n", 1),
		),
	).
		Msg("hello world")

}

Output:

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

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

Source: event.go:518

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

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

Source: event.go:527

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

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

Source: event.go:379

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 (e *Event) Caller(skip ...int) *Event

Source: event.go:858

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 (e *Event) CallerSkipFrame(skip int) *Event

Source: event.go:847

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

func (e *Event) CreateArray() *Array

Source: event.go:216

CreateArray creates an Array to be used with the *Event.Array method. It preserves the stack, hooks, and context from the parent event. Call usual field methods like Str, Int etc to add elements to this array and give it as argument the *Event.Array method.

func (e *Event) CreateDict() *Event

Source: event.go:195

CreateDict creates an Event to be used with the *Event.Dict method. It preserves the stack, hooks, and context from the parent event. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the *Event.Dict method.

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

Source: event.go:499

Ctx adds the Go Context to the *Event context. The context is not rendered in the output message, but is available to hooks and to Func() calls via the GetCtx() accessor. A typical use case is to extract tracing information from the Go Ctx.

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

Source: event.go:182

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

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

	e := log.Log().
		Str("foo", "bar")

	e.Dict("dict", e.CreateDict().
		Str("bar", "baz").
		Int("n", 1),
	).
		Msg("hello world")

}

Output:

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

func (e *Event) Discard() *Event

Source: event.go:103

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

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

Source: event.go:785

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 (e *Event) Durs(key string, d []time.Duration) *Event

Source: event.go:796

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 (e *Event) EmbedObject(obj LogObjectMarshaler) *Event

Source: event.go:303

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 (e *Event) Enabled() bool

Source: event.go:98

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

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

Source: event.go:461

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 (e *Event) Errs(key string, errs []error) *Event

Source: event.go:445

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

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

Source: event.go:172

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.

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

Source: event.go:716

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

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

Source: event.go:734

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

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

Source: event.go:725

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

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

Source: event.go:743

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

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

Source: event.go:295

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

func (e *Event) GetCtx() context.Context

Source: event.go:510

GetCtx retrieves the Go context.Context which is optionally stored in the Event. This allows Hooks and functions passed to Func() to retrieve values which are stored in the context.Context. This can be useful in tracing, where span information is commonly propagated in the context.Context.

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

Source: event.go:388

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

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

Source: event.go:877

IPAddr adds the field key with ip as a net.IP IPv4 or IPv6 Address to the event

func (e *Event) IPAddrs(key string, ip []net.IP) *Event

Source: event.go:886

IPAddrs adds the field key with ip as a net.IP array of IPv4 or IPv6 Address to the event

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

Source: event.go:895

IPPrefix adds the field key with pfx as a net.IPNet IPv4 or IPv6 Prefix (address and mask) to the event

func (e *Event) IPPrefixes(key string, pfx []net.IPNet) *Event

Source: event.go:904

IPPrefixes the field key with pfx as a net.IPNet array of IPv4 or IPv6 Prefixes (address and mask) to the event

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

Source: event.go:536

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

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

Source: event.go:572

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

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

Source: event.go:590

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

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

Source: event.go:608

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

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

Source: event.go:554

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

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

Source: event.go:825

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 (e *Event) Ints(key string, i []int) *Event

Source: event.go:545

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

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

Source: event.go:581

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

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

Source: event.go:599

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

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

Source: event.go:617

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

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

Source: event.go:563

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

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

Source: event.go:913

MACAddr the field key with ha as a net.HardwareAddr MAC address to the event

func (e *Event) Msg(msg string)

Source: event.go:115

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 (e *Event) MsgFunc(createMsg func() string)

Source: event.go:143

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

Source: event.go:136

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 (e *Event) Object(key string, obj LogObjectMarshaler) *Event

Source: event.go:252

Object marshals an object that implement the LogObjectMarshaler interface.

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

	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 (e *Event) Objects(key string, objs []LogObjectMarshaler) *Event

Source: event.go:271

Objects adds the field key with objs as an array of objects that implement the LogObjectMarshaler interface to the event.

This is the array version that accepts a slice of LogObjectMarshaler objects.

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

	u := User{"John", 35, time.Time{}}
	u2 := User{"Bono", 54, time.Time{}}
	users := []User{u, u2}

	log.Log().
		Objects("users", zerolog.AsLogObjectMarshalers(users)).
		Msg("hello world")

}

Output:

{"users":[{"name":"John","age":35,"created":"0001-01-01T00:00:00Z"},{"name":"Bono","age":54,"created":"0001-01-01T00:00:00Z"}],"message":"hello world"}

func (e *Event) ObjectsV(key string, objs ...LogObjectMarshaler) *Event

Source: event.go:290

ObjectsV adds the field key with objs as an array of objects that implement the LogObjectMarshaler interface to the event.

This is a variadic version that accepts a list of individual LogObjectMarshaler objects.

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

	u := User{"John", 35, time.Time{}}
	u2 := User{"Bono", 54, time.Time{}}

	log.Log().
		ObjectsV("users", u, u2).
		Msg("hello world")

}

Output:

{"users":[{"name":"John","age":35,"created":"0001-01-01T00:00:00Z"},{"name":"Bono","age":54,"created":"0001-01-01T00:00:00Z"}],"message":"hello world"}

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

Source: event.go:412

RawCBOR adds already encoded CBOR to the log line under key.

No sanity check is performed on b Note: The full featureset of CBOR is supported as data will not be mapped to json but stored as data-url

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

Source: event.go:400

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 (e *Event) Send()

Source: event.go:125

Send is equivalent to calling Msg("").

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

func (e *Event) Stack() *Event

Source: event.go:488

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

ErrorStackMarshaler must be set for this method to do something.

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

Source: event.go:315

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

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

Source: event.go:344

Stringer adds the field key and a val to the *Event context. If val is not nil, it is added by calling val.String(). If val is nil, it is encoded as null without calling String().

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

Source: event.go:357

Stringers adds the field key with vals to the *Event context. If a val is not nil, it is added by calling val.String(). If a val is nil, it is encoded as null without calling String().

This is the array version that accepts a slice of fmt.Stringer values.

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

	a := net.IP{127, 0, 0, 1}
	b := net.IP{127, 0, 0, 2}
	ips := []net.IP{a, b}

	log.Log().
		Stringers("ips", zerolog.AsStringers(ips)).
		Msg("hello world")

}

Output:

{"ips":["127.0.0.1","127.0.0.2"],"message":"hello world"}

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

Source: event.go:371

StringersV adds the field key with vals to the *Event context. If a val is not nil, it is added by calling val.String(). If a val is nil, it is encoded as null without calling String().

This is a variadic version that accepts a list of individual fmt.Stringer values.

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

Source: event.go:326

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

This is the array version that accepts a slice of string values.

func (e *Event) StrsV(key string, vals ...string) *Event

Source: event.go:337

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

This is a variadic version that accepts a list of individual strings.

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

Source: event.go:765

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

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

Source: event.go:807

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 (e *Event) Times(key string, t []time.Time) *Event

Source: event.go:774

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

func (e *Event) Timestamp() *Event

Source: event.go:756

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 (e *Event) Type(key string, val interface{}) *Event

Source: event.go:837

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

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

Source: event.go:626

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

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

Source: event.go:662

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

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

Source: event.go:680

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

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

Source: event.go:698

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

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

Source: event.go:644

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

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

Source: event.go:635

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

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

Source: event.go:671

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

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

Source: event.go:689

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

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

Source: event.go:707

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

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

Source: event.go:653

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

type FilteredLevelWriter

Source: writer.go:197

FilteredLevelWriter writes only logs at Level or above to Writer.

It should be used only in combination with MultiLevelWriter when you want to write to multiple destinations at different levels. Otherwise you should just set the level on the logger and filter events early. When using MultiLevelWriter then you set the level on the logger to the lowest of the levels you use for writers.

type FilteredLevelWriter struct {
	Writer LevelWriter
	Level  Level
}
Fields
  • Writer LevelWriter
  • Level Level

func (w *FilteredLevelWriter) Close() error

Source: writer.go:218

Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.

func (w *FilteredLevelWriter) Write(p []byte) (int, error)

Source: writer.go:203

Write writes to the underlying Writer.

func (w *FilteredLevelWriter) WriteLevel(level Level, p []byte) (int, error)

Source: writer.go:209

WriteLevel calls WriteLevel of the underlying Writer only if the level is equal or above the Level.

type Formatter

Source: console.go:48

Formatter transforms the input into a formatted string.

type Formatter func(interface{}) string

type FormatterByFieldName

Source: console.go:52

FormatterByFieldName transforms the input into a formatted string, being able to differentiate formatting based on field name.

type FormatterByFieldName func(interface{}, string) string

type Hook

Source: hook.go:4

Hook defines an interface to a log hook.

type Hook interface {
	// Run runs the hook with the event.
	Run(e *Event, level Level, message string)
}
Methods
  • Run func(e *Event, level Level, message string)

    Run runs the hook with the event.

type HookFunc

Source: hook.go:11

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

type HookFunc func(e *Event, level Level, message string)

func (h HookFunc) Run(e *Event, level Level, message string)

Source: hook.go:14

Run implements the Hook interface.

type Level

Source: log.go:127

Level defines log levels.

type Level int8

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

Source: log.go:221

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

func (l Level) String() string

Source: log.go:152

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

Source: log.go:211

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

type LevelHook

Source: hook.go:19

LevelHook applies a different hook for each level.

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

func (h LevelHook) Run(e *Event, level Level, message string)

Source: hook.go:24

Run implements the Hook interface.

type LevelSampler

Source: sampler.go:106

LevelSampler applies a different sampler for each level.

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

func (s LevelSampler) Sample(lvl Level) bool

Source: sampler.go:110

type LevelWriter

Source: writer.go:15

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

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

type LevelWriterAdapter

Source: writer.go:21

LevelWriterAdapter adapts an io.Writer to support the LevelWriter interface.

type LevelWriterAdapter struct {
	io.Writer
}
Fields
  • io.Writer

func (lw LevelWriterAdapter) Close() error

Source: writer.go:32

Call the underlying writer's Close method if it is an io.Closer. Otherwise does nothing.

func (lw LevelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error)

Source: writer.go:26

WriteLevel simply writes everything to the adapted writer, ignoring the level.

type LogArrayMarshaler

Source: event.go:64

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

type LogArrayMarshaler interface {
	MarshalZerologArray(a *Array)
}
Methods
  • MarshalZerologArray func(a *Array)

type LogObjectMarshaler

Source: event.go:58

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

type LogObjectMarshaler interface {
	MarshalZerologObject(e *Event)
}
Methods
  • MarshalZerologObject func(e *Event)

type Logger

Source: log.go:230

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.

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

func (l *Logger) Debug() *Event

Source: log.go:350

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 (l *Logger) Err(err error) *Event

Source: log.go:379

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 (l *Logger) Error() *Event

Source: log.go:371

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 (l *Logger) Fatal() *Event

Source: log.go:392

Fatal starts a new message with fatal level. The FatalExitFunc interceptor function is called by the Msg method, which by default terminates the program immediately using os.Exit(1), any desired behavior can be implemented by setting FatalExitFunc.

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

func (l Logger) GetLevel() Level

Source: log.go:319

GetLevel returns the current Level of l.

func (l Logger) Hook(hooks ...Hook) Logger

Source: log.go:330

Hook returns a logger with the h Hook.

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

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

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

}

Output:

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

func (l *Logger) Info() *Event

Source: log.go:357

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 (l Logger) Level(lvl Level) Logger

Source: log.go:313

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 (l *Logger) Log() *Event

Source: log.go:450

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 (l Logger) Output(w io.Writer) Logger

Source: log.go:264

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

func (l *Logger) Panic() *Event

Source: log.go:412

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 (l *Logger) Print(v ...interface{})

Source: log.go:456

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 (l *Logger) Printf(format string, v ...interface{})

Source: log.go:464

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 (l *Logger) Println(v ...interface{})

Source: log.go:472

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

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

	log.Println("hello world")

}

Output:

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

func (l Logger) Sample(s Sampler) Logger

Source: log.go:324

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 (l *Logger) Trace() *Event

Source: log.go:343

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 (l *Logger) UpdateContext(update func(c Context) Context)

Source: log.go:298

UpdateContext updates the internal logger's context.

Caution: This method is not concurrency safe. Use the With method to create a child logger before modifying the context from concurrent goroutines.

func (l *Logger) Warn() *Event

Source: log.go:364

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 (l Logger) With() Context

Source: log.go:281

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 (l Logger) WithContext(ctx context.Context) context.Context

Source: ctx.go:33

WithContext returns a copy of ctx with the receiver attached. The Logger attached to the provided Context (if any) will not be affected. 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 (l *Logger) WithLevel(level Level) *Event

Source: log.go:421

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 (l Logger) Write(p []byte) (n int, err error)

Source: log.go:480

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

Source: sampler.go:27

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

type RandomSampler uint32

func (s RandomSampler) Sample(lvl Level) bool

Source: sampler.go:30

Sample implements the Sampler interface.

type Sampler

Source: sampler.go:19

Sampler defines an interface to a log sampler.

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
}
Methods
  • Sample func(lvl Level) bool

    Sample returns true if the event should be part of the sample, false if the event should be dropped.

type SlogHandler

Source: slog.go:12

SlogHandler implements the slog.Handler interface using a zerolog.Logger as the underlying log backend. This allows code that uses the standard library's slog package to route log output through zerolog.

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

func (h *SlogHandler) Enabled(_ context.Context, level slog.Level) bool

Source: slog.go:27

Enabled reports whether the handler handles records at the given level. It mirrors Logger.should's level and writer checks (without sampling).

func (h *SlogHandler) Handle(ctx context.Context, record slog.Record) error

Source: slog.go:40

Handle handles the Record. It converts the slog.Record into a zerolog event and writes it using the underlying zerolog.Logger.

func (h *SlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

Source: slog.go:88

WithAttrs returns a new Handler with the given attributes pre-attached. These attributes will be included in every subsequent log record.

func (h *SlogHandler) WithGroup(name string) slog.Handler

Source: slog.go:99

WithGroup returns a new Handler with the given group name. All subsequent attributes will be nested under this group name in the output.

type SyslogWriter

Source: syslog.go:15

SyslogWriter is an interface matching a syslog.Writer struct.

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
}
Methods
  • io.Writer
  • Debug func(m string) error
  • Info func(m string) error
  • Warning func(m string) error
  • Err func(m string) error
  • Emerg func(m string) error
  • Crit func(m string) error

type TestWriter

Source: writer.go:147

TestWriter is a writer that writes to testing.TB.

type TestWriter struct {
	T TestingLog

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

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

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

Source: writer.go:160

Write to testing.TB.

type TestingLog

Source: writer.go:140

TestingLog is the logging interface of testing.TB.

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

type TriggerLevelWriter

Source: writer.go:237

TriggerLevelWriter buffers log lines at the ConditionalLevel or below until a trigger level (or higher) line is emitted. Log lines with level higher than ConditionalLevel are always written out to the destination writer. If trigger never happens, buffered log lines are never written out.

It can be used to configure "log level per request".

type TriggerLevelWriter struct {
	// Destination writer. If LevelWriter is provided (usually), its WriteLevel is used
	// instead of Write.
	io.Writer

	// ConditionalLevel is the level (and below) at which lines are buffered until
	// a trigger level (or higher) line is emitted. Usually this is set to DebugLevel.
	ConditionalLevel Level

	// TriggerLevel is the lowest level that triggers the sending of the conditional
	// level lines. Usually this is set to ErrorLevel.
	TriggerLevel Level
	// contains filtered or unexported fields
}
Fields
  • io.Writer

    Destination writer. If LevelWriter is provided (usually), its WriteLevel is used instead of Write.

  • ConditionalLevel Level

    ConditionalLevel is the level (and below) at which lines are buffered until a trigger level (or higher) line is emitted. Usually this is set to DebugLevel.

  • TriggerLevel Level

    TriggerLevel is the lowest level that triggers the sending of the conditional level lines. Usually this is set to ErrorLevel.

func (w *TriggerLevelWriter) Close() error

Source: writer.go:337

Close closes the writer and returns the buffer to the pool.

func (w *TriggerLevelWriter) Trigger() error

Source: writer.go:329

Trigger forces flushing the buffer and change the trigger state to triggered, if the writer has not already been triggered before.

func (w *TriggerLevelWriter) WriteLevel(l Level, p []byte) (n int, err error)

Source: writer.go:255

Edit this page

Sourcey-generated documentation mirror for rs/zerolog (MIT), built from source at a pinned commit.Docs by Sourcey