Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

zerolog

v1.35.1
github.com/rs/zerolog

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

369 matches

Top ↑

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

A global Logger can be use 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 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.

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

TimeFormatUnix (7 declarations)

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

Variables

TimestampFieldName (31 declarations)

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
)

Often (3 declarations)

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

AsStringers

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

ConsoleTestWriter

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

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

DisableSampling

func DisableSampling(v bool)

DisableSampling will disable sampling in all Loggers if true.

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.

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

Array

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.

Arr

func Arr() *Array

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.

Array.Bool

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

Bool appends the val as a bool to the array.

Array.Bytes

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

Bytes appends the val as a string to the array.

Array.Dict

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

Dict adds the dict Event to the array

Array.Dur

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

Dur appends d to the array.

Array.Err

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

Err serializes and appends the err to the array.

Array.Errs

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

Errs serializes and appends errors to the array.

Array.Float32

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

Float32 appends f as a float32 to the array.

Array.Float64

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

Float64 appends f as a float64 to the array.

Array.Hex

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

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

Array.IPAddr

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

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

Array.IPPrefix

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

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

Array.Int

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

Int appends i as a int to the array.

Array.Int16

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

Int16 appends i as a int16 to the array.

Array.Int32

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

Int32 appends i as a int32 to the array.

Array.Int64

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

Int64 appends i as a int64 to the array.

Array.Int8

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

Int8 appends i as a int8 to the array.

Array.Interface

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

Interface appends i marshaled using reflection.

Array.MACAddr

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

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

Array.MarshalZerologArray

func (*Array) MarshalZerologArray(*Array)

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

Array.Object

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

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

Array.RawJSON

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

RawJSON adds already encoded JSON to the array.

Array.Str

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

Str appends the val as a string to the array.

Array.Time

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

Time appends t formatted as string using zerolog.TimeFieldFormat.

Array.Type

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

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

Array.Uint

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

Uint appends i as a uint to the array.

Array.Uint16

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

Uint16 appends i as a uint16 to the array.

Array.Uint32

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

Uint32 appends i as a uint32 to the array.

Array.Uint64

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

Uint64 appends i as a uint64 to the array.

Array.Uint8

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

Uint8 appends i as a uint8 to the array.

BasicSampler

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

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

Showing entries 1–40 of 265. Use Contents to jump to any section or symbol.

Dependency graph