zerolog package - github.com/rs/zerolog - Go Packages

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

View Source

const (
	
	
	TimeFormatUnix = ""

	
	
	TimeFormatUnixMs = "UNIXMS"

	
	
	TimeFormatUnixMicro = "UNIXMICRO"

	
	
	TimeFormatUnixNano = "UNIXNANO"
)

View Source

var (
	
	TimestampFieldName = "time"

	
	LevelFieldName = "level"

	
	LevelTraceValue = "trace"
	
	LevelDebugValue = "debug"
	
	LevelInfoValue = "info"
	
	LevelWarnValue = "warn"
	
	LevelErrorValue = "error"
	
	LevelFatalValue = "fatal"
	
	LevelPanicValue = "panic"

	
	LevelFieldMarshalFunc = func(l Level) string {
		return l.String()
	}

	
	MessageFieldName = "message"

	
	ErrorFieldName = "error"

	
	CallerFieldName = "caller"

	
	CallerSkipFrameCount = 2

	
	CallerMarshalFunc = func(pc uintptr, file string, line int) string {
		return file + ":" + strconv.Itoa(line)
	}

	
	ErrorStackFieldName = "stack"

	
	ErrorStackMarshaler func(err error) interface{}

	
	ErrorMarshalFunc = func(err error) interface{} {
		return err
	}

	
	
	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 = time.RFC3339

	
	TimestampFunc = time.Now

	
	
	DurationFieldUnit = time.Millisecond

	
	
	DurationFieldInteger = false

	
	
	
	ErrorHandler func(err error)

	
	
	DefaultContextLogger *Logger

	
	
	LevelColors = map[Level]int{
		TraceLevel: colorBlue,
		DebugLevel: 0,
		InfoLevel:  colorGreen,
		WarnLevel:  colorYellow,
		ErrorLevel: colorRed,
		FatalLevel: colorRed,
		PanicLevel: colorRed,
	}

	
	
	FormattedLevels = map[Level]string{
		TraceLevel: "TRC",
		DebugLevel: "DBG",
		InfoLevel:  "INF",
		WarnLevel:  "WRN",
		ErrorLevel: "ERR",
		FatalLevel: "FTL",
		PanicLevel: "PNC",
	}

	
	
	TriggerLevelWriterBufferReuseLimit = 64 * 1024

	
	
	
	FloatingPointPrecision = -1
)
func ConsoleTestWriter(t TestingLog) func(w *ConsoleWriter)

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

func DisableSampling(v bool)

DisableSampling will disable sampling in all Loggers if true.

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

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

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

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

Bool appends the val as a bool to the array.

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

Bytes appends the val as a string to the array.

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

Dict adds the dict Event to the array

Dur appends d to the array.

Err serializes and appends the err to the array.

Float32 appends f as a float32 to the array.

Float64 appends f as a float64 to the array.

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

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

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

IPAddr adds IPv4 or IPv6 address to the array

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

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

Int appends i as a int to the array.

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

Int8 appends i as a int8 to the array.

Int16 appends i as a int16 to the array.

Int32 appends i as a int32 to the array.

Int64 appends i as a int64 to the array.

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

Interface appends i marshaled using reflection.

MACAddr adds a MAC (Ethernet) address to the array

func (*Array) MarshalZerologArray(*Array)

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

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

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

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

RawJSON adds already encoded JSON to the array.

Str appends the val as a string to the array.

Time appends t formatted as string using zerolog.TimeFieldFormat.

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

Uint appends i as a uint to the array.

Uint8 appends i as a uint8 to the array.

Uint16 appends i as a uint16 to the array.

Uint32 appends i as a uint32 to the array.

Uint64 appends i as a uint64 to the array.

type BasicSampler struct {
	N uint32
	
}

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

Sample implements the Sampler interface.

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

Sample implements the Sampler interface.

type ConsoleWriter struct {
	
	Out io.Writer

	
	NoColor bool

	
	TimeFormat string

	
	
	TimeLocation *time.Location

	
	PartsOrder []string

	
	PartsExclude []string

	
	FieldsOrder []string

	
	FieldsExclude []string

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


	FormatPrepare func(map[string]interface{}) error
	
}

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/rs/zerolog"
)

func main() {
	out := zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true}
	out.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%-6s|", i)) }
	out.FormatFieldName = func(i interface{}) string { return fmt.Sprintf("%s:", i) }
	out.FormatFieldValue = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%s", i)) }
	log := zerolog.New(out)

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

<nil> INFO  | Hello World foo:BAR
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/rs/zerolog"
)

func main() {
	out := zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true,
		PartsOrder:    []string{"level", "one", "two", "three", "message"},
		FieldsExclude: []string{"one", "two", "three"}}
	out.FormatLevel = func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%-6s", i)) }
	out.FormatFieldName = func(i interface{}) string { return fmt.Sprintf("%s:", i) }
	out.FormatPartValueByName = func(i interface{}, s string) string {
		var ret string
		switch s {
		case "one":
			ret = strings.ToUpper(fmt.Sprintf("%s", i))
		case "two":
			ret = strings.ToLower(fmt.Sprintf("%s", i))
		case "three":
			ret = strings.ToLower(fmt.Sprintf("(%s)", i))
		}
		return ret
	}
	log := zerolog.New(out)

	log.Info().Str("foo", "bar").
		Str("two", "TEST_TWO").
		Str("one", "test_one").
		Str("three", "test_three").
		Msg("Hello World")
}
Output:

INFO   TEST_ONE test_two (test_three) Hello World foo:bar
func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter

NewConsoleWriter creates and initializes a new ConsoleWriter.

package main

import (
	"github.com/rs/zerolog"
)

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

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

<nil> DBG Hello World foo=bar
package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/rs/zerolog"
)

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

	log := zerolog.New(out)

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

<nil> [INFO ] Hello World foo=bar

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

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

Context configures a new sub-logger with contextual fields.

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

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

Any is a wrapper around Context.Interface.

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.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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"}
package main

import (
	"os"
	"time"

	"github.com/rs/zerolog"
)

type User struct {
	Name    string
	Age     int
	Created time.Time
}

func (u User) MarshalZerologObject(e *zerolog.Event) {
	e.Str("name", u.Name).
		Int("age", u.Age).
		Time("created", u.Created)
}

type Users []User

func (uu Users) MarshalZerologArray(a *zerolog.Array) {
	for _, u := range uu {
		a.Object(u)
	}
}

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

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

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

}
Output:

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

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

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

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

func (c Context) Caller() Context

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

func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context

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

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.

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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"}

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

package main

import (
	"os"
	"time"

	"github.com/rs/zerolog"
)

func main() {
	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"}

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

package main

import (
	"os"
	"time"

	"github.com/rs/zerolog"
)

func main() {
	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

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

package main

import (
	"fmt"
	"os"

	"github.com/rs/zerolog"
)

type Price struct {
	val  uint64
	prec int
	unit string
}

func (p Price) MarshalZerologObject(e *zerolog.Event) {
	denom := uint64(1)
	for i := 0; i < p.prec; i++ {
		denom *= 10
	}
	result := []byte(p.unit)
	result = append(result, fmt.Sprintf("%d.%d", p.val/denom, p.val%denom)...)
	e.Str("price", string(result))
}

func main() {

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

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

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

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

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

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

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

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

}
Output:

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

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	fields := []interface{}{
		"bar", "baz",
		"n", 1,
	}

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

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

}
Output:

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

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

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

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

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

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

IPAddr adds IPv4 or IPv6 Address to the context

package main

import (
	"net"
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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"}

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

package main

import (
	"net"
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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"}

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

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

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

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

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

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

Interface adds the field key with obj marshaled using reflection.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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"}

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

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

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

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

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

func (c Context) Logger() Logger

Logger returns the logger with the context previously set.

MACAddr adds MAC address to the context

package main

import (
	"net"
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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"}

Object marshals an object that implement the LogObjectMarshaler interface.

package main

import (
	"os"
	"time"

	"github.com/rs/zerolog"
)

type User struct {
	Name    string
	Age     int
	Created time.Time
}

func (u User) MarshalZerologObject(e *zerolog.Event) {
	e.Str("name", u.Name).
		Int("age", u.Age).
		Time("created", u.Created)
}

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

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

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

}
Output:

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

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

Reset removes all the context fields.

func (c Context) Stack() Context

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

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

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

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

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

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

func (c Context) Timestamp() Context

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Any is a wrapper around Event.Interface.

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.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	log := zerolog.New(os.Stdout)

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

}
Output:

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

import (
	"os"
	"time"

	"github.com/rs/zerolog"
)

type User struct {
	Name    string
	Age     int
	Created time.Time
}

func (u User) MarshalZerologObject(e *zerolog.Event) {
	e.Str("name", u.Name).
		Int("age", u.Age).
		Time("created", u.Created)
}

type Users []User

func (uu Users) MarshalZerologArray(a *zerolog.Array) {
	for _, u := range uu {
		a.Object(u)
	}
}

func main() {
	log := zerolog.New(os.Stdout)

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

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

}
Output:

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

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

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

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

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

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

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.

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	log := zerolog.New(os.Stdout)

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

}
Output:

{"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}
func (e *Event) Discard() *Event

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

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.

package main

import (
	"os"
	"time"

	"github.com/rs/zerolog"
)

func main() {
	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"}

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.

package main

import (
	"os"
	"time"

	"github.com/rs/zerolog"
)

func main() {
	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

EmbedObject marshals an object that implement the LogObjectMarshaler interface.

package main

import (
	"fmt"
	"os"

	"github.com/rs/zerolog"
)

type Price struct {
	val  uint64
	prec int
	unit string
}

func (p Price) MarshalZerologObject(e *zerolog.Event) {
	denom := uint64(1)
	for i := 0; i < p.prec; i++ {
		denom *= 10
	}
	result := []byte(p.unit)
	result = append(result, fmt.Sprintf("%d.%d", p.val/denom, p.val%denom)...)
	e.Str("price", string(result))
}

func main() {
	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

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

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.

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

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

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

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

	log := zerolog.New(os.Stdout)

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

}
Output:

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

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	fields := []interface{}{
		"bar", "baz",
		"n", 1,
	}

	log := zerolog.New(os.Stdout)

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

}
Output:

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

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

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

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

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

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

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

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.

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

IPAddr adds IPv4 or IPv6 Address to the event

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

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

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

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

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

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

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

Interface adds the field key with i marshaled using reflection.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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"}

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

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

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

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

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

MACAddr adds MAC address to the event

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)
func (e *Event) Msgf(format string, v ...interface{})

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

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

Object marshals an object that implement the LogObjectMarshaler interface.

package main

import (
	"os"
	"time"

	"github.com/rs/zerolog"
)

type User struct {
	Name    string
	Age     int
	Created time.Time
}

func (u User) MarshalZerologObject(e *zerolog.Event) {
	e.Str("name", u.Name).
		Int("age", u.Age).
		Time("created", u.Created)
}

func main() {
	log := zerolog.New(os.Stdout)

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

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

}
Output:

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

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

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.

Send is equivalent to calling Msg("").

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

func (e *Event) Stack() *Event

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

ErrorStackMarshaler must be set for this method to do something.

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

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

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

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

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

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

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

func (e *Event) Timestamp() *Event

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type FilteredLevelWriter struct {
	Writer LevelWriter
	Level  Level
}

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.

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

Write writes to the underlying Writer.

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

type Formatter func(interface{}) string

Formatter transforms the input into a formatted string.

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

type Hook interface {
	
	Run(e *Event, level Level, message string)
}

Hook defines an interface to a log hook.

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

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

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

Run implements the Hook interface.

Level defines log levels.

const (
	
	DebugLevel Level = iota
	
	InfoLevel
	
	WarnLevel
	
	ErrorLevel
	
	FatalLevel
	
	PanicLevel
	
	NoLevel
	
	Disabled

	
	TraceLevel Level = -1
)

GlobalLevel returns the current global log level

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

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

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

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

LevelHook applies a different hook for each level.

func NewLevelHook() LevelHook

NewLevelHook returns a new LevelHook.

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

Run implements the Hook interface.

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

LevelSampler applies a different sampler for each level.

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

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

func SyslogCEEWriter(w SyslogWriter) LevelWriter

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

func SyslogLevelWriter(w SyslogWriter) LevelWriter

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

type LevelWriterAdapter struct {
	io.Writer
}

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

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

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

type LogArrayMarshaler interface {
	MarshalZerologArray(a *Array)
}

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

type LogObjectMarshaler 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.

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.

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.

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.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	log := zerolog.New(os.Stdout)

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

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

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

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.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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"}

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

Error starts a new message with error level.

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

package main

import (
	"errors"
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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

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

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

func (l Logger) GetLevel() Level

GetLevel returns the current Level of l.

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

Hook returns a logger with the h Hook.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

type LevelNameHook struct{}

func (h LevelNameHook) Run(e *zerolog.Event, l zerolog.Level, msg string) {
	if l != zerolog.NoLevel {
		e.Str("level_name", l.String())
	} else {
		e.Str("level_name", "NoLevel")
	}
}

type MessageHook string

func (h MessageHook) Run(e *zerolog.Event, l zerolog.Level, msg string) {
	e.Str("the_message", msg)
}

func main() {
	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

Info starts a new message with info level.

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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

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.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	log := zerolog.New(os.Stdout)

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

}
Output:

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

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

func (l *Logger) Panic() *Event

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

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

func (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.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	log := zerolog.New(os.Stdout)

	log.Print("hello world")

}
Output:

{"level":"debug","message":"hello world"}
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.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	log := zerolog.New(os.Stdout)

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

}
Output:

{"level":"debug","message":"hello world"}
func (l *Logger) Println(v ...interface{})

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	log := zerolog.New(os.Stdout)

	log.Println("hello world")

}
Output:

{"level":"debug","message":"hello world\n"}
func (l Logger) Sample(s Sampler) Logger

Sample returns a logger with the s sampler.

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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

Trace starts a new message with trace level.

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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)

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

Warn starts a new message with warn level.

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	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

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

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

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

}
Output:

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

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

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

ctx := r.Context()
l := zerolog.Ctx(ctx)
l.UpdateContext(func(c Context) Context {
    return c.Str("bar", "baz")
})
func (l *Logger) WithLevel(level Level) *Event

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

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

package main

import (
	"os"

	"github.com/rs/zerolog"
)

func main() {
	log := zerolog.New(os.Stdout)

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

}
Output:

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

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

package main

import (
	stdlog "log"
	"os"

	"github.com/rs/zerolog"
)

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

	stdlog.SetFlags(0)
	stdlog.SetOutput(log)

	stdlog.Print("hello world")

}
Output:

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

type RandomSampler added in v1.3.0

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

func (RandomSampler) Sample added in v1.3.0

Sample implements the Sampler interface.

type Sampler interface {
	
	
	Sample(lvl Level) bool
}

Sampler defines an interface to a log sampler.

SyslogWriter is an interface matching a syslog.Writer struct.

type TestWriter struct {
	T TestingLog

	
	Frame int
}

TestWriter is a writer that writes to testing.TB.

func NewTestWriter(t TestingLog) TestWriter

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

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

TestingLog is the logging interface of testing.TB.

type TriggerLevelWriter struct {
	
	
	io.Writer

	
	
	ConditionalLevel Level

	
	
	TriggerLevel Level
	
}

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

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

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