zerolog
v1.7.0
Documentation
pkg.go.dev ↗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
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"}
However, it’s not a big deal though as JSON accepts dup keys, the last one prevails.
Variables
TimestampFieldName (10 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" // 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 // TimeFieldFormat defines the time format of the Time field type. // If set to an empty string, the time is formatted as an 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 )
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
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 the call to writer's Write method is not thread safe. Note that os.File Write operation is using write() syscall which is supposed to be thread-safe on POSIX systems. So there is no need to use this with os.File on such systems as zerolog guaranties to issue a single Write call per log event.
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.
Array.Bool
func (a *Array) Bool(b bool) *Array
Bool enc.Append the val as a bool to the array.
Array.Bytes
func (a *Array) Bytes(val []byte) *Array
Bytes enc.Append the val as a string to the array.
Array.Dur
func (a *Array) Dur(d time.Duration) *Array
Dur enc.Append d to the array.
Array.Err
func (a *Array) Err(err error) *Array
Err enc.Append the err as a string to the array.
Array.Float32
func (a *Array) Float32(f float32) *Array
Float32 enc.Append f as a float32 to the array.
Array.Float64
func (a *Array) Float64(f float64) *Array
Float64 enc.Append f as a float64 to the array.
Array.Hex
func (a *Array) Hex(val []byte) *Array
Hex enc.Append the val as a hex string to the array.
Array.IPAddr
func (a *Array) IPAddr(ip net.IP) *Array
IPAddr adds IPv4 or IPv6 address to the array
Array.IPPrefix
func (a *Array) IPPrefix(pfx net.IPNet) *Array
IPPrefix adds IPv4 or IPv6 Prefix (IP + mask) to the array
Array.Int
func (a *Array) Int(i int) *Array
Int enc.Append i as a int to the array.
Array.Int16
func (a *Array) Int16(i int16) *Array
Int16 enc.Append i as a int16 to the array.
Array.Int32
func (a *Array) Int32(i int32) *Array
Int32 enc.Append i as a int32 to the array.
Array.Int64
func (a *Array) Int64(i int64) *Array
Int64 enc.Append i as a int64 to the array.
Array.Int8
func (a *Array) Int8(i int8) *Array
Int8 enc.Append i as a int8 to the array.
Array.Interface
func (a *Array) Interface(i interface{}) *Array
Interface enc.Append i marshaled using reflection.
Array.MACAddr
func (a *Array) MACAddr(ha net.HardwareAddr) *Array
MACAddr adds a 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 enc.Append it to the array.
Array.Str
func (a *Array) Str(val string) *Array
Str enc.Append the val as a string to the array.
Array.Time
func (a *Array) Time(t time.Time) *Array
Time enc.Append t formated as string using zerolog.TimeFieldFormat.
Array.Uint
func (a *Array) Uint(i uint) *Array
Uint enc.Append i as a uint to the array.
Array.Uint16
func (a *Array) Uint16(i uint16) *Array
Uint16 enc.Append i as a uint16 to the array.
Array.Uint32
func (a *Array) Uint32(i uint32) *Array
Uint32 enc.Append i as a uint32 to the array.
Array.Uint64
func (a *Array) Uint64(i uint64) *Array
Uint64 enc.Append i as a uint64 to the array.
Array.Uint8
func (a *Array) Uint8(i uint8) *Array
Uint8 enc.Append 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 there level.
BasicSampler.Sample
func (s *BasicSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
BurstSampler
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.
BurstSampler.Sample
func (s *BurstSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
ConsoleWriter
type ConsoleWriter struct {
Out io.Writer
NoColor bool
}
ConsoleWriter reads a JSON object per write operation and output an optionally colored human readable version on the Out writer.
ConsoleWriter.Write
func (w ConsoleWriter) Write(p []byte) (n int, err error)
Example
{
log := zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true})
log.Info().Msg("hello world")
}
Output:
<nil> |INFO| hello world
Context
type Context struct {
// contains filtered or unexported fields
}
Context configures a new sub-logger with contextual fields.
Context.AnErr
func (c Context) AnErr(key string, err error) Context
AnErr adds the field key with err as a string to the logger context.
Context.Array
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)
{
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"}
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.
Context.Bools
func (c Context) Bools(key string, b []bool) Context
Bools adds the field key with val as a []bool to the logger context.
Context.Bytes
func (c Context) Bytes(key string, val []byte) Context
Bytes adds the field key with val as a []byte to the logger context.
Context.Caller
func (c Context) Caller() Context
Caller adds the file:line of the caller with the zerolog.CallerFieldName key.
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"}
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 := time.Duration(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"}
Context.Durs
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{
time.Duration(10 * time.Second),
time.Duration(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"}
Context.EmbedObject
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"}
Context.Err
func (c Context) Err(err error) Context
Err adds the field "error" with err as a string to the logger context. To customize the key name, change zerolog.ErrorFieldName.
Context.Errs
func (c Context) Errs(key string, errs []error) Context
Errs adds the field key with errs as an array of strings to the logger context.
Context.Fields
func (c Context) Fields(fields map[string]interface{}) Context
Fields is a helper function to use a map to set fields using type assertion.
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.
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.
Context.Floats32
func (c Context) Floats32(key string, f []float32) Context
Floats32 adds the field key with f as a []float32 to the logger context.
Context.Floats64
func (c Context) Floats64(key string, f []float64) Context
Floats64 adds the field key with f as a []float64 to the logger context.
Context.Hex
func (c Context) Hex(key string, val []byte) Context
Hex adds the field key with val as a hex string to the logger context.
Context.IPAddr
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"}
Context.IPPrefix
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"}
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.
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.
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.
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.
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.
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"}
Context.Ints
func (c Context) Ints(key string, i []int) Context
Ints adds the field key with i as a []int to the logger context.
Context.Ints16
func (c Context) Ints16(key string, i []int16) Context
Ints16 adds the field key with i as a []int16 to the logger context.
Context.Ints32
func (c Context) Ints32(key string, i []int32) Context
Ints32 adds the field key with i as a []int32 to the logger context.
Context.Ints64
func (c Context) Ints64(key string, i []int64) Context
Ints64 adds the field key with i as a []int64 to the logger context.
Context.Ints8
func (c Context) Ints8(key string, i []int8) Context
Ints8 adds the field key with i as a []int8 to the logger context.
Context.Logger
func (c Context) Logger() Logger
Logger returns the logger with the context previously set.
Context.MACAddr
func (c Context) MACAddr(key string, ha net.HardwareAddr) Context
MACAddr adds MAC address to the context
Context.Object
func (c Context) Object(key string, obj LogObjectMarshaler) Context
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"}
Context.RawJSON
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.
Context.Str
func (c Context) Str(key, val string) Context
Str adds the field key with val as a string to the logger context.
Context.Strs
func (c Context) Strs(key string, vals []string) Context
Strs adds the field key with val as a string to the logger context.
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.
Context.Times
func (c Context) Times(key string, t []time.Time) Context
Times adds the field key with t formated as string using zerolog.TimeFieldFormat.
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.
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.
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.
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.
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.
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.
Context.Uints
func (c Context) Uints(key string, i []uint) Context
Uints adds the field key with i as a []uint to the logger context.
Context.Uints16
func (c Context) Uints16(key string, i []uint16) Context
Uints16 adds the field key with i as a []uint16 to the logger context.
Context.Uints32
func (c Context) Uints32(key string, i []uint32) Context
Uints32 adds the field key with i as a []uint32 to the logger context.
Context.Uints64
func (c Context) Uints64(key string, i []uint64) Context
Uints64 adds the field key with i as a []uint64 to the logger context.
Context.Uints8
func (c Context) Uints8(key string, i []uint8) Context
Uints8 adds the field key with i as a []uint8 to the logger context.
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.
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.
Event.AnErr
func (e *Event) AnErr(key string, err error) *Event
AnErr adds the field key with err as a string to the *Event context. If err is nil, no field is added.
Event.Array
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),
).
Msg("hello world")
}
Output:
{"foo":"bar","array":["baz",1],"message":"hello world"}
Example (object)
{
log := zerolog.New(os.Stdout)
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"}
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.
Event.Bools
func (e *Event) Bools(key string, b []bool) *Event
Bools adds the field key with val as a []bool to the *Event context.
Event.Bytes
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.
Event.Caller
func (e *Event) Caller() *Event
Caller adds the file:line of the caller with the zerolog.CallerFieldName key.
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"}
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 := time.Duration(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"}
Event.Durs
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{
time.Duration(10 * time.Second),
time.Duration(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"}
Event.EmbedObject
func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event
Object 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"}
Event.Enabled
func (e *Event) Enabled() bool
Enabled return false if the *Event is going to be filtered out by log level or sampling.
Event.Err
func (e *Event) Err(err error) *Event
Err adds the field "error" with err as a string to the *Event context. If err is nil, no field is added. To customize the key name, change zerolog.ErrorFieldName.
Event.Errs
func (e *Event) Errs(key string, errs []error) *Event
Errs adds the field key with errs as an array of strings to the *Event context. If err is nil, no field is added.
Event.Fields
func (e *Event) Fields(fields map[string]interface{}) *Event
Fields is a helper function to use a map to set fields using type assertion.
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.
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.
Event.Floats32
func (e *Event) Floats32(key string, f []float32) *Event
Floats32 adds the field key with f as a []float32 to the *Event context.
Event.Floats64
func (e *Event) Floats64(key string, f []float64) *Event
Floats64 adds the field key with f as a []float64 to the *Event context.
Event.Hex
func (e *Event) Hex(key string, val []byte) *Event
Hex adds the field key with val as a hex string to the *Event context.
Event.IPAddr
func (e *Event) IPAddr(key string, ip net.IP) *Event
IPAddr adds IPv4 or IPv6 Address to the event
Event.IPPrefix
func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event
IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the event
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.
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.
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.
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.
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.
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"}
Event.Ints
func (e *Event) Ints(key string, i []int) *Event
Ints adds the field key with i as a []int to the *Event context.
Event.Ints16
func (e *Event) Ints16(key string, i []int16) *Event
Ints16 adds the field key with i as a []int16 to the *Event context.
Event.Ints32
func (e *Event) Ints32(key string, i []int32) *Event
Ints32 adds the field key with i as a []int32 to the *Event context.
Event.Ints64
func (e *Event) Ints64(key string, i []int64) *Event
Ints64 adds the field key with i as a []int64 to the *Event context.
Event.Ints8
func (e *Event) Ints8(key string, i []int8) *Event
Ints8 adds the field key with i as a []int8 to the *Event context.
Event.MACAddr
func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event
MACAddr adds MAC address to the event
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.
Event.Msgf
func (e *Event) Msgf(format string, v ...interface{})
Msgf sends the event with formated msg added as the message field if not empty.
NOTICE: once this methid is called, the *Event should be disposed. Calling Msg twice can have unexpected result.
Event.Object
func (e *Event) Object(key string, obj LogObjectMarshaler) *Event
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"}
Event.RawJSON
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.
Event.Str
func (e *Event) Str(key, val string) *Event
Str adds the field key with val as a string to the *Event context.
Event.Strs
func (e *Event) Strs(key string, vals []string) *Event
Strs adds the field key with vals as a []string to the *Event context.
Event.Time
func (e *Event) Time(key string, t time.Time) *Event
Time adds the field key with t formated as string using zerolog.TimeFieldFormat.
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().
Event.Times
func (e *Event) Times(key string, t []time.Time) *Event
Times adds the field key with t formated as string using zerolog.TimeFieldFormat.
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.
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.
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.
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.
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.
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.
Event.Uints
func (e *Event) Uints(key string, i []uint) *Event
Uints adds the field key with i as a []int to the *Event context.
Event.Uints16
func (e *Event) Uints16(key string, i []uint16) *Event
Uints16 adds the field key with i as a []int16 to the *Event context.
Event.Uints32
func (e *Event) Uints32(key string, i []uint32) *Event
Uints32 adds the field key with i as a []int32 to the *Event context.
Event.Uints64
func (e *Event) Uints64(key string, i []uint64) *Event
Uints64 adds the field key with i as a []int64 to the *Event context.
Event.Uints8
func (e *Event) Uints8(key string, i []uint8) *Event
Uints8 adds the field key with i as a []int8 to the *Event context.
Hook
type Hook interface {
// Run runs the hook with the event.
Run(e *Event, level Level, message string)
}
Hook defines an interface to a log hook.
Level
type Level uint8
Level defines log levels.
DebugLevel (8 declarations)
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 )
GlobalLevel
func GlobalLevel() Level
GlobalLevel returns the current global log level
ParseLevel
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.
Level.String
func (l Level) String() string
LevelHook
type LevelHook struct {
NoLevelHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook
}
LevelHook applies a different hook for each level.
NewLevelHook
func NewLevelHook() LevelHook
NewLevelHook returns a new LevelHook.
LevelHook.Run
func (h LevelHook) Run(e *Event, level Level, message string)
Run implements the Hook interface.
LevelSampler
type LevelSampler struct {
DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler
}
LevelSampler applies a different sampler for each level.
LevelSampler.Sample
func (s LevelSampler) Sample(lvl Level) bool
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.
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.
SyslogLevelWriter
func SyslogLevelWriter(w SyslogWriter) LevelWriter
SyslogLevelWriter wraps a SyslogWriter and call the right syslog level method matching the zerolog level.
LogArrayMarshaler
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.
LogObjectMarshaler
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.
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 guaranty on access serialization to the Writer. If your Writer is not thread safe, you may consider a sync wrapper.
Ctx
func Ctx(ctx context.Context) *Logger
Ctx returns the Logger associated with the ctx. If no logger is associated, a disabled logger is returned.
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 guaranty 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"}
Nop
func Nop() Logger
Nop returns a disabled logger for which all operation are no-op.
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"}
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"}
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.
You must call Msg on the returned event in order to send the event.
Logger.Hook
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"}
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"}
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"}
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"}
Logger.Output
func (l Logger) Output(w io.Writer) Logger
Output duplicates the current logger and sets w as its output.
Logger.Panic
func (l *Logger) Panic() *Event
Panic starts a new message with panic level. The message is also sent to the panic function.
You must call Msg on the returned event in order to send the event.
Logger.Print
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"}
Logger.Printf
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"}
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 2"}
{"level":"info","message":"message 4"}
Logger.UpdateContext
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.
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"}
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"}
Logger.WithContext
func (l Logger) WithContext(ctx context.Context) context.Context
WithContext returns a copy of ctx with l associated. If an instance of Logger is already in the context, the pointer to this logger is updated with l.
For instance, to add a field to an existing logger in the context, use this notation:
ctx := r.Context()
l := zerolog.Ctx(ctx)
ctx = l.With().Str("foo", "bar").WithContext(ctx)
Logger.WithLevel
func (l *Logger) WithLevel(level Level) *Event
WithLevel starts a new message with level.
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"}
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"}
RandomSampler
type RandomSampler uint32
RandomSampler use a PRNG to randomly sample an event out of N events, regardless of their level.
RandomSampler.Sample
func (s RandomSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
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
}
Sampler defines an interface to a log sampler.
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.