Documentation ¶
Overview ¶
Package zerolog provides a lightweight logging library dedicated to JSON logging.
A global Logger can be use for simple logging:
import "go.innotegrity.dev/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 "go.innotegrity.dev/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"}
In this case, many consumers will take the last value, but this is not guaranteed; check yours if in doubt.
Index ¶
- Constants
- Variables
- func ConsoleTestWriter(t TestingLog) func(w *ConsoleWriter)
- func DisableSampling(v bool)
- func SetGlobalLevel(l Level)
- func SyncWriter(w io.Writer) io.Writer
- type Array
- func (a *Array) Bool(b bool) *Array
- func (a *Array) Bytes(val []byte) *Array
- func (a *Array) Dict(dict *Event) *Array
- func (a *Array) Dur(d time.Duration) *Array
- func (a *Array) Err(err error) *Array
- func (a *Array) Float32(f float32) *Array
- func (a *Array) Float64(f float64) *Array
- func (a *Array) Hex(val []byte) *Array
- func (a *Array) IPAddr(ip net.IP) *Array
- func (a *Array) IPPrefix(pfx net.IPNet) *Array
- func (a *Array) Int(i int) *Array
- func (a *Array) Int16(i int16) *Array
- func (a *Array) Int32(i int32) *Array
- func (a *Array) Int64(i int64) *Array
- func (a *Array) Int8(i int8) *Array
- func (a *Array) Interface(i interface{}) *Array
- func (a *Array) MACAddr(ha net.HardwareAddr) *Array
- func (*Array) MarshalZerologArray(*Array)
- func (a *Array) Object(obj LogObjectMarshaler) *Array
- func (a *Array) RawJSON(val []byte) *Array
- func (a *Array) Str(val string) *Array
- func (a *Array) Time(t time.Time) *Array
- func (a *Array) Uint(i uint) *Array
- func (a *Array) Uint16(i uint16) *Array
- func (a *Array) Uint32(i uint32) *Array
- func (a *Array) Uint64(i uint64) *Array
- func (a *Array) Uint8(i uint8) *Array
- type BasicSampler
- type BurstSampler
- type ConsoleWriter
- type Context
- func (c Context) AnErr(key string, err error) Context
- func (c Context) Array(key string, arr LogArrayMarshaler) Context
- func (c Context) Bool(key string, b bool) Context
- func (c Context) Bools(key string, b []bool) Context
- func (c Context) Bytes(key string, val []byte) Context
- func (c Context) Caller() Context
- func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context
- func (c Context) Dict(key string, dict *Event) Context
- func (c Context) Dur(key string, d time.Duration) Context
- func (c Context) Durs(key string, d []time.Duration) Context
- func (c Context) EmbedObject(obj LogObjectMarshaler) Context
- func (c Context) Err(err error) Context
- func (c Context) Errs(key string, errs []error) Context
- func (c Context) Fields(fields interface{}) Context
- func (c Context) Float32(key string, f float32) Context
- func (c Context) Float64(key string, f float64) Context
- func (c Context) Floats32(key string, f []float32) Context
- func (c Context) Floats64(key string, f []float64) Context
- func (c Context) Hex(key string, val []byte) Context
- func (c Context) IPAddr(key string, ip net.IP) Context
- func (c Context) IPPrefix(key string, pfx net.IPNet) Context
- func (c Context) Int(key string, i int) Context
- func (c Context) Int16(key string, i int16) Context
- func (c Context) Int32(key string, i int32) Context
- func (c Context) Int64(key string, i int64) Context
- func (c Context) Int8(key string, i int8) Context
- func (c Context) Interface(key string, i interface{}) Context
- func (c Context) Ints(key string, i []int) Context
- func (c Context) Ints16(key string, i []int16) Context
- func (c Context) Ints32(key string, i []int32) Context
- func (c Context) Ints64(key string, i []int64) Context
- func (c Context) Ints8(key string, i []int8) Context
- func (c Context) Logger() Logger
- func (c Context) MACAddr(key string, ha net.HardwareAddr) Context
- func (c Context) Object(key string, obj LogObjectMarshaler) Context
- func (c Context) RawJSON(key string, b []byte) Context
- func (c Context) Stack() Context
- func (c Context) Str(key, val string) Context
- func (c Context) Stringer(key string, val fmt.Stringer) Context
- func (c Context) Strs(key string, vals []string) Context
- func (c Context) Time(key string, t time.Time) Context
- func (c Context) Times(key string, t []time.Time) Context
- func (c Context) Timestamp() Context
- func (c Context) Uint(key string, i uint) Context
- func (c Context) Uint16(key string, i uint16) Context
- func (c Context) Uint32(key string, i uint32) Context
- func (c Context) Uint64(key string, i uint64) Context
- func (c Context) Uint8(key string, i uint8) Context
- func (c Context) Uints(key string, i []uint) Context
- func (c Context) Uints16(key string, i []uint16) Context
- func (c Context) Uints32(key string, i []uint32) Context
- func (c Context) Uints64(key string, i []uint64) Context
- func (c Context) Uints8(key string, i []uint8) Context
- type Event
- func (e *Event) AnErr(key string, err error) *Event
- func (e *Event) Any(key string, i interface{}) *Event
- func (e *Event) Array(key string, arr LogArrayMarshaler) *Event
- func (e *Event) Bool(key string, b bool) *Event
- func (e *Event) Bools(key string, b []bool) *Event
- func (e *Event) Bytes(key string, val []byte) *Event
- func (e *Event) Caller(skip ...int) *Event
- func (e *Event) CallerSkipFrame(skip int) *Event
- func (e *Event) Dict(key string, dict *Event) *Event
- func (e *Event) Discard() *Event
- func (e *Event) Dur(key string, d time.Duration) *Event
- func (e *Event) Durs(key string, d []time.Duration) *Event
- func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event
- func (e *Event) Enabled() bool
- func (e *Event) Err(err error) *Event
- func (e *Event) Errs(key string, errs []error) *Event
- func (e *Event) Fields(fields interface{}) *Event
- func (e *Event) Float32(key string, f float32) *Event
- func (e *Event) Float64(key string, f float64) *Event
- func (e *Event) Floats32(key string, f []float32) *Event
- func (e *Event) Floats64(key string, f []float64) *Event
- func (e *Event) Func(f func(e *Event)) *Event
- func (e *Event) Hex(key string, val []byte) *Event
- func (e *Event) IPAddr(key string, ip net.IP) *Event
- func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event
- func (e *Event) Int(key string, i int) *Event
- func (e *Event) Int16(key string, i int16) *Event
- func (e *Event) Int32(key string, i int32) *Event
- func (e *Event) Int64(key string, i int64) *Event
- func (e *Event) Int8(key string, i int8) *Event
- func (e *Event) Interface(key string, i interface{}) *Event
- func (e *Event) Ints(key string, i []int) *Event
- func (e *Event) Ints16(key string, i []int16) *Event
- func (e *Event) Ints32(key string, i []int32) *Event
- func (e *Event) Ints64(key string, i []int64) *Event
- func (e *Event) Ints8(key string, i []int8) *Event
- func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event
- func (e *Event) Msg(msg string)
- func (e *Event) MsgFunc(createMsg func() string)
- func (e *Event) Msgf(format string, v ...interface{})
- func (e *Event) Object(key string, obj LogObjectMarshaler) *Event
- func (e *Event) RawCBOR(key string, b []byte) *Event
- func (e *Event) RawJSON(key string, b []byte) *Event
- func (e *Event) Send()
- func (e *Event) Stack() *Event
- func (e *Event) Str(key, val string) *Event
- func (e *Event) Stringer(key string, val fmt.Stringer) *Event
- func (e *Event) Stringers(key string, vals []fmt.Stringer) *Event
- func (e *Event) Strs(key string, vals []string) *Event
- func (e *Event) Time(key string, t time.Time) *Event
- func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event
- func (e *Event) Times(key string, t []time.Time) *Event
- func (e *Event) Timestamp() *Event
- func (e *Event) Type(key string, val interface{}) *Event
- func (e *Event) Uint(key string, i uint) *Event
- func (e *Event) Uint16(key string, i uint16) *Event
- func (e *Event) Uint32(key string, i uint32) *Event
- func (e *Event) Uint64(key string, i uint64) *Event
- func (e *Event) Uint8(key string, i uint8) *Event
- func (e *Event) Uints(key string, i []uint) *Event
- func (e *Event) Uints16(key string, i []uint16) *Event
- func (e *Event) Uints32(key string, i []uint32) *Event
- func (e *Event) Uints64(key string, i []uint64) *Event
- func (e *Event) Uints8(key string, i []uint8) *Event
- type FilteredLevelWriter
- type Formatter
- type Hook
- type HookFunc
- type JSONWriter
- type Level
- type LevelHook
- type LevelSampler
- type LevelWriter
- type LogArrayMarshaler
- type LogObjectMarshaler
- type Logger
- func (l *Logger) Debug() *Event
- func (l *Logger) Err(err error) *Event
- func (l *Logger) Error() *Event
- func (l *Logger) Fatal() *Event
- func (l Logger) GetLevel() Level
- func (l Logger) Hook(h Hook) Logger
- func (l *Logger) Info() *Event
- func (l *Logger) InterceptLogrusMessages(writer *io.PipeWriter)
- func (l *Logger) IsDebugEnabled() bool
- func (l Logger) Level(lvl Level) Logger
- func (l *Logger) Log() *Event
- func (l Logger) Output(w io.Writer) Logger
- func (l *Logger) Panic() *Event
- func (l *Logger) ParseLogrusMessages(reader *io.PipeReader, handler ParseLogrusMessageErrorHandler)
- func (l *Logger) Print(v ...interface{})
- func (l *Logger) Printf(format string, v ...interface{})
- func (l Logger) Sample(s Sampler) Logger
- func (l *Logger) SetLevel(level Level)
- func (l *Logger) Trace() *Event
- func (l *Logger) UpdateContext(update func(c Context) Context)
- func (l *Logger) Warn() *Event
- func (l Logger) With() Context
- func (l Logger) WithContext(ctx context.Context) context.Context
- func (l *Logger) WithLevel(level Level) *Event
- func (l *Logger) WouldLog(level Level) bool
- func (l Logger) Write(p []byte) (n int, err error)
- type ParseLogrusMessageErrorHandler
- type RandomSampler
- type Sampler
- type SyslogWriter
- type TestWriter
- type TestingLog
Examples ¶
- ConsoleWriter
- ConsoleWriter (CustomFormatters)
- Context.Array
- Context.Array (Object)
- Context.Dict
- Context.Dur
- Context.Durs
- Context.EmbedObject
- Context.Fields (Map)
- Context.Fields (Slice)
- Context.IPAddr
- Context.IPPrefix
- Context.Interface
- Context.MACAddr
- Context.Object
- Event.Array
- Event.Array (Object)
- Event.Dict
- Event.Dur
- Event.Durs
- Event.EmbedObject
- Event.Fields (Map)
- Event.Fields (Slice)
- Event.Interface
- Event.Object
- Logger.Debug
- Logger.Error
- Logger.Hook
- Logger.Info
- Logger.Level
- Logger.Log
- Logger.Print
- Logger.Printf
- Logger.Sample
- Logger.Trace
- Logger.Warn
- Logger.With
- Logger.WithLevel
- Logger.Write
- New
- NewConsoleWriter
- NewConsoleWriter (CustomFormatters)
Constants ¶
const ( // TimeFormatUnix defines a time format that makes time fields to be // serialized as Unix timestamp integers. TimeFormatUnix = "" // TimeFormatUnixMs defines a time format that makes time fields to be // serialized as Unix timestamp integers in milliseconds. TimeFormatUnixMs = "UNIXMS" // TimeFormatUnixMicro defines a time format that makes time fields to be // serialized as Unix timestamp integers in microseconds. TimeFormatUnixMicro = "UNIXMICRO" // TimeFormatUnixNano defines a time format that makes time fields to be // serialized as Unix timestamp integers in nanoseconds. TimeFormatUnixNano = "UNIXNANO" )
Variables ¶
var ( // TimestampFieldName is the field name used for the timestamp field. TimestampFieldName = "time" // LevelFieldName is the field name used for the level field. LevelFieldName = "level" // LevelTraceValue is the value used for the trace level field. LevelTraceValue = "trace" // LevelDebugValue is the value used for the debug level field. LevelDebugValue = "debug" // LevelInfoValue is the value used for the info level field. LevelInfoValue = "info" // LevelWarnValue is the value used for the warn level field. LevelWarnValue = "warn" // LevelErrorValue is the value used for the error level field. LevelErrorValue = "error" // LevelFatalValue is the value used for the fatal level field. LevelFatalValue = "fatal" // LevelPanicValue is the value used for the panic level field. LevelPanicValue = "panic" // LevelFieldMarshalFunc allows customization of global level field marshaling. LevelFieldMarshalFunc = func(l Level) string { return l.String() } // MessageFieldName is the field name used for the message field. MessageFieldName = "message" // ErrorFieldName is the field name used for error fields. ErrorFieldName = "error" // CallerFieldName is the field name used for caller field. CallerFieldName = "caller" // CallerSkipFrameCount is the number of stack frames to skip to find the caller. CallerSkipFrameCount = 2 // CallerMarshalFunc allows customization of global caller marshaling CallerMarshalFunc = func(pc uintptr, file string, line int) string { return file + ":" + strconv.Itoa(line) } // ErrorStackFieldName is the field name used for error stacks. ErrorStackFieldName = "stack" // ErrorStackMarshaler extract the stack from err if any. ErrorStackMarshaler func(err error) interface{} // ErrorMarshalFunc allows customization of global error marshaling ErrorMarshalFunc = func(err error) interface{} { return err } // InterfaceMarshalFunc allows customization of interface marshaling. // Default: "encoding/json.Marshal" InterfaceMarshalFunc = json.Marshal // TimeFieldFormat defines the time format of the Time field type. If set to // TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX // timestamp as integer. TimeFieldFormat = time.RFC3339 // TimestampFunc defines the function called to generate a timestamp. TimestampFunc = time.Now // DurationFieldUnit defines the unit for time.Duration type fields added // using the Dur method. DurationFieldUnit = time.Millisecond // DurationFieldInteger renders Dur fields as integer instead of float if // set to true. DurationFieldInteger = false // ErrorHandler is called whenever zerolog fails to write an event on its // output. If not set, an error is printed on the stderr. This handler must // be thread safe and non-blocking. ErrorHandler func(err error) // DefaultContextLogger is returned from Ctx() if there is no logger associated // with the context. DefaultContextLogger *Logger )
var ( // Often samples log every ~ 10 events. Often = RandomSampler(10) // Sometimes samples log every ~ 100 events. Sometimes = RandomSampler(100) // Rarely samples log every ~ 1000 events. Rarely = RandomSampler(1000) )
Functions ¶
func ConsoleTestWriter ¶
func ConsoleTestWriter(t TestingLog) func(w *ConsoleWriter)
ConsoleTestWriter creates an option that correctly sets the file frame depth for testing.TB log.
func DisableSampling ¶
func DisableSampling(v bool)
DisableSampling will disable sampling in all Loggers if true.
func SetGlobalLevel ¶
func SetGlobalLevel(l Level)
SetGlobalLevel sets the global override for log level. If this values is raised, all Loggers will use at least this value.
To globally disable logs, set GlobalLevel to Disabled.
func SyncWriter ¶
SyncWriter wraps w so that each call to Write is synchronized with a mutex. This syncer can be used to wrap the call to writer's Write method if it is not thread safe. Note that you do not need this wrapper for os.File Write operations on POSIX and Windows systems as they are already thread-safe.
Types ¶
type Array ¶
type Array struct {
// contains filtered or unexported fields
}
Array is used to prepopulate an array of items which can be re-used to add to log messages.
func (*Array) MACAddr ¶
func (a *Array) MACAddr(ha net.HardwareAddr) *Array
MACAddr adds a MAC (Ethernet) address to the array
func (*Array) MarshalZerologArray ¶
MarshalZerologArray method here is no-op - since data is already in the needed format.
func (*Array) Object ¶
func (a *Array) Object(obj LogObjectMarshaler) *Array
Object marshals an object that implement the LogObjectMarshaler interface and appends it to the array.
type 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.
func (*BasicSampler) Sample ¶
func (s *BasicSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
type 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.
func (*BurstSampler) Sample ¶
func (s *BurstSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
type ConsoleWriter ¶
type ConsoleWriter struct { /** END CUSTOM CODE */ // Out is the output destination. Out io.Writer // NoColor disables the colorized output. NoColor bool // TimeFormat specifies the format for timestamp in output. TimeFormat string // PartsOrder defines the order of parts in output. PartsOrder []string // PartsExclude defines parts to not display in output. PartsExclude []string // FieldsExclude defines contextual fields to not display in output. FieldsExclude []string FormatTimestamp Formatter FormatLevel Formatter FormatCaller Formatter FormatMessage Formatter FormatFieldName Formatter FormatFieldValue Formatter FormatErrFieldName Formatter FormatErrFieldValue Formatter FormatExtra func(map[string]interface{}, *bytes.Buffer) error /** BEGIN CUSTOM CODE */ CallerFieldName string ErrorFieldName string ErrorStackFieldName string LevelFieldName string MessageFieldName string TimestampFieldName string }
ConsoleWriter parses the JSON input and writes it in an (optionally) colorized, human-friendly format to Out.
Unlike using the global `zerolog.CallerFieldName` value to change the caller name for all log writers, you can use the writer's `CallerFieldName` to change the name only for this writer.
By default if a field name is not provided, the global field name will be used instead. When excluding fields from the output, be sure to use the DEFAULT field name and NOT the customized field name.
Example ¶
package main import ( "os" "go.innotegrity.dev/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
Example (CustomFormatters) ¶
package main import ( "fmt" "os" "strings" "go.innotegrity.dev/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
func NewConsoleWriter ¶
func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter
NewConsoleWriter creates and initializes a new ConsoleWriter.
Example ¶
package main import ( "go.innotegrity.dev/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
Example (CustomFormatters) ¶
package main import ( "fmt" "strings" "time" "go.innotegrity.dev/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
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context configures a new sub-logger with contextual fields.
func (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 ¶
package main import ( "os" "go.innotegrity.dev/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"}
Example (Object) ¶
package main import ( "os" "time" "go.innotegrity.dev/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"}
func (Context) Caller ¶
Caller adds the file:line of the caller with the zerolog.CallerFieldName key.
func (Context) CallerWithSkipFrameCount ¶
CallerWithSkipFrameCount adds the file:line of the caller with the zerolog.CallerFieldName key. The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger. If set to -1 the global CallerSkipFrameCount will be used.
func (Context) Dict ¶
Dict adds the field key with the dict to the logger context.
Example ¶
package main import ( "os" "go.innotegrity.dev/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"}
func (Context) Dur ¶
Dur adds the fields key with d divided by unit and stored as a float.
Example ¶
package main import ( "os" "time" "go.innotegrity.dev/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"}
func (Context) Durs ¶
Durs adds the fields key with d divided by unit and stored as a float.
Example ¶
package main import ( "os" "time" "go.innotegrity.dev/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 (Context) EmbedObject ¶
func (c Context) EmbedObject(obj LogObjectMarshaler) Context
EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface.
Example ¶
package main import ( "fmt" "os" "go.innotegrity.dev/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"}
func (Context) Errs ¶
Errs adds the field key with errs as an array of serialized errors to the logger context.
func (Context) Fields ¶
Fields is a helper function to use a map or slice to set fields using type assertion. Only map[string]interface{} and []interface{} are accepted. []interface{} must alternate string keys and arbitrary values, and extraneous ones are ignored.
Example (Map) ¶
package main import ( "os" "go.innotegrity.dev/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"}
Example (Slice) ¶
package main import ( "os" "go.innotegrity.dev/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"}
func (Context) IPAddr ¶
IPAddr adds IPv4 or IPv6 Address to the context
Example ¶
package main import ( "net" "os" "go.innotegrity.dev/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"}
func (Context) IPPrefix ¶
IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the context
Example ¶
package main import ( "net" "os" "go.innotegrity.dev/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"}
func (Context) Interface ¶
Interface adds the field key with obj marshaled using reflection.
Example ¶
package main import ( "os" "go.innotegrity.dev/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"}
func (Context) MACAddr ¶
func (c Context) MACAddr(key string, ha net.HardwareAddr) Context
MACAddr adds MAC address to the context
Example ¶
package main import ( "net" "os" "go.innotegrity.dev/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"}
func (Context) Object ¶
func (c Context) Object(key string, obj LogObjectMarshaler) Context
Object marshals an object that implement the LogObjectMarshaler interface.
Example ¶
package main import ( "os" "time" "go.innotegrity.dev/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"}
func (Context) RawJSON ¶
RawJSON adds already encoded JSON to context.
No sanity check is performed on b; it must not contain carriage returns and be valid JSON.
func (Context) Stringer ¶
Stringer adds the field key with val.String() (or null if val is nil) to the logger context.
func (Context) Time ¶
Time adds the field key with t formated as string using zerolog.TimeFieldFormat.
func (Context) Times ¶
Times adds the field key with t formated as string using zerolog.TimeFieldFormat.
func (Context) Timestamp ¶
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.
type Event ¶
type Event struct {
// contains filtered or unexported fields
}
Event represents a log event. It is instanced by one of the level method of Logger and finalized by the Msg or Msgf method.
func Dict ¶
func Dict() *Event
Dict creates an Event to be used with the *Event.Dict method. Call usual field methods like Str, Int etc to add fields to this event and give it as argument the *Event.Dict method.
func (*Event) AnErr ¶
AnErr adds the field key with serialized err to the *Event context. If err is nil, no field is added.
func (*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 ¶
package main import ( "os" "go.innotegrity.dev/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"}
Example (Object) ¶
package main import ( "os" "time" "go.innotegrity.dev/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"}
func (*Event) Bytes ¶
Bytes adds the field key with val as a string to the *Event context.
Runes outside of normal ASCII ranges will be hex-encoded in the resulting JSON.
func (*Event) Caller ¶
Caller adds the file:line of the caller with the zerolog.CallerFieldName key. The argument skip is the number of stack frames to ascend Skip If not passed, use the global variable CallerSkipFrameCount
func (*Event) CallerSkipFrame ¶
CallerSkipFrame instructs any future Caller calls to skip the specified number of frames. This includes those added via hooks from the context.
func (*Event) Dict ¶
Dict adds the field key with a dict to the event context. Use zerolog.Dict() to create the dictionary.
Example ¶
package main import ( "os" "go.innotegrity.dev/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 (*Event) Dur ¶
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 ¶
package main import ( "os" "time" "go.innotegrity.dev/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"}
func (*Event) Durs ¶
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 ¶
package main import ( "os" "time" "go.innotegrity.dev/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 (*Event) EmbedObject ¶
func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event
EmbedObject marshals an object that implement the LogObjectMarshaler interface.
Example ¶
package main import ( "fmt" "os" "go.innotegrity.dev/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 (*Event) Enabled ¶
Enabled return false if the *Event is going to be filtered out by log level or sampling.
func (*Event) Err ¶
Err adds the field "error" with serialized err to the *Event context. If err is nil, no field is added.
To customize the key name, change zerolog.ErrorFieldName.
If Stack() has been called before and zerolog.ErrorStackMarshaler is defined, the err is passed to ErrorStackMarshaler and the result is appended to the zerolog.ErrorStackFieldName.
func (*Event) Errs ¶
Errs adds the field key with errs as an array of serialized errors to the *Event context.
func (*Event) Fields ¶
Fields is a helper function to use a map or slice to set fields using type assertion. Only map[string]interface{} and []interface{} are accepted. []interface{} must alternate string keys and arbitrary values, and extraneous ones are ignored.
Example (Map) ¶
package main import ( "os" "go.innotegrity.dev/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"}
Example (Slice) ¶
package main import ( "os" "go.innotegrity.dev/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"}
func (*Event) Interface ¶
Interface adds the field key with i marshaled using reflection.
Example ¶
package main import ( "os" "go.innotegrity.dev/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"}
func (*Event) MACAddr ¶
func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event
MACAddr adds MAC address to the event
func (*Event) Msg ¶
Msg sends the *Event with msg added as the message field if not empty.
NOTICE: once this method is called, the *Event should be disposed. Calling Msg twice can have unexpected result.
func (*Event) Msgf ¶
Msgf sends the event with formatted msg added as the message field if not empty.
NOTICE: once this method is called, the *Event should be disposed. Calling Msgf twice can have unexpected result.
func (*Event) Object ¶
func (e *Event) Object(key string, obj LogObjectMarshaler) *Event
Object marshals an object that implement the LogObjectMarshaler interface.
Example ¶
package main import ( "os" "time" "go.innotegrity.dev/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"}
func (*Event) RawCBOR ¶
RawCBOR adds already encoded CBOR to the log line under key.
No sanity check is performed on b Note: The full featureset of CBOR is supported as data will not be mapped to json but stored as data-url
func (*Event) RawJSON ¶
RawJSON adds already encoded JSON to the log line under key.
No sanity check is performed on b; it must not contain carriage returns and be valid JSON.
func (*Event) Send ¶
func (e *Event) Send()
Send is equivalent to calling Msg("").
NOTICE: once this method is called, the *Event should be disposed.
func (*Event) Stack ¶
Stack enables stack trace printing for the error passed to Err().
ErrorStackMarshaler must be set for this method to do something.
func (*Event) Stringer ¶
Stringer adds the field key with val.String() (or null if val is nil) to the *Event context.
func (*Event) Stringers ¶
Stringers adds the field key with vals where each individual val is used as val.String() (or null if val is empty) to the *Event context.
func (*Event) Time ¶
Time adds the field key with t formatted as string using zerolog.TimeFieldFormat.
func (*Event) TimeDiff ¶
TimeDiff adds the field key with positive duration between time t and start. If time t is not greater than start, duration will be 0. Duration format follows the same principle as Dur().
func (*Event) Times ¶
Times adds the field key with t formatted as string using zerolog.TimeFieldFormat.
func (*Event) Timestamp ¶
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.
type FilteredLevelWriter ¶
type FilteredLevelWriter struct {
// contains filtered or unexported fields
}
FilteredLevelWriter will only output messages that have a specific level.
This writer can be used to filter specific message levels into a particular output file or stream. You can specify as many or as few levels as you'd like. Any messages with levels that are NOT a part of this list will NOT be logged regardless of what the logger's global level is set to.
It should be noted that in order for a message to be processed by this writer, the logger itself must be set to the correct level as well. For example, if the logger is only set to log warning or greater messages, debug and info messages will still not be logged by this writer as they will not ever reach it. The general rule is to set the logger to the lowest level of messages you'd like to log and then filter higher level messages out as desired.
func NewFilteredLevelWriter ¶
func NewFilteredLevelWriter(levels []Level, w io.Writer) *FilteredLevelWriter
NewFilteredLevelwriter creates and returns a new FilteredLevelWriter object.
func (*FilteredLevelWriter) SetLevels ¶
func (w *FilteredLevelWriter) SetLevels(levels []Level)
SetLevels updates the levels of messages that will be logged by this writer.
func (*FilteredLevelWriter) Write ¶
func (w *FilteredLevelWriter) Write(p []byte) (int, error)
Write simply writes the message out.
func (*FilteredLevelWriter) WriteLevel ¶
func (w *FilteredLevelWriter) WriteLevel(level Level, p []byte) (int, error)
WriteLevel is called to write a message at a particular level.
Only messages matching one of the filter levels will be logged. Other messages are effectively discarded.
type Formatter ¶
type Formatter func(interface{}) string
Formatter transforms the input into a formatted string.
type 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.
type JSONWriter ¶ added in v1.30.1
type JSONWriter struct { // Out is the output destination. Out io.Writer // TimeFormat specifies the format for timestamp in output. TimeFormat string // ExcludeFields defines fields to exclude in the output. ExcludeFields []string // CallerFieldName defines the name of the caller field. CallerFieldName string // ErrorFieldName defines the name of the error field. ErrorFieldName string // ErrorStackFieldName defines the name of the error stack field. ErrorStackFieldName string // LevelFieldName defines the name of the level field. LevelFieldName string // MessageFieldName defines the name of the message field. MessageFieldName string // TimestampFieldName defines the name of the timestamp field. TimestampFieldName string }
JSONWriter is a custom JSON-formatted writer that changes the default field names for this and only this writer.
Unlike using the global `zerolog.CallerFieldName` value to change the caller name for all log writers, you can use the writer's `CallerFieldName` to change the name only for this writer.
By default if a field name is not provided, the global field name will be used instead. When excluding fields from the output, be sure to use the customized field name if one was set.
NOTE: Be aware that this writer may not be as efficient as the built-in JSON writer as the normal JSON is unmarshaled to a generic map[string]interface{} object and then re-marshaled after being updated.
func NewJSONWriter ¶ added in v1.30.1
func NewJSONWriter() JSONWriter
NewJSONWriter creates and initializes a new JSONWriter.
type Level ¶
type Level int8
Level defines log levels.
const ( // DebugLevel defines debug log level. DebugLevel Level = iota // InfoLevel defines info log level. InfoLevel // WarnLevel defines warn log level. WarnLevel // ErrorLevel defines error log level. ErrorLevel // FatalLevel defines fatal log level. FatalLevel // PanicLevel defines panic log level. PanicLevel // NoLevel defines an absent log level. NoLevel // Disabled disables the logger. Disabled // TraceLevel defines trace log level. TraceLevel Level = -1 )
func ParseLevel ¶
ParseLevel converts a level string into a zerolog Level value. returns an error if the input string does not match known values.
func (Level) MarshalText ¶
MarshalText implements encoding.TextMarshaler to allow for easy writing into toml/yaml/json formats
func (*Level) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler to allow for easy reading from toml/yaml/json formats
type LevelHook ¶
type LevelHook struct {
NoLevelHook, TraceHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook
}
LevelHook applies a different hook for each level.
type LevelSampler ¶
type LevelSampler struct {
TraceSampler, DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler
}
LevelSampler applies a different sampler for each level.
func (LevelSampler) Sample ¶
func (s LevelSampler) Sample(lvl Level) bool
type LevelWriter ¶
LevelWriter defines as interface a writer may implement in order to receive level information with payload.
func MultiLevelWriter ¶
func MultiLevelWriter(writers ...io.Writer) LevelWriter
MultiLevelWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command. If some writers implement LevelWriter, their WriteLevel method will be used instead of Write.
func SyslogCEEWriter ¶
func SyslogCEEWriter(w SyslogWriter) LevelWriter
SyslogCEEWriter wraps a SyslogWriter with a SyslogLevelWriter that adds a MITRE CEE prefix for JSON syslog entries, compatible with rsyslog and syslog-ng JSON logging support. See https://www.rsyslog.com/json-elasticsearch/
func SyslogLevelWriter ¶
func SyslogLevelWriter(w SyslogWriter) LevelWriter
SyslogLevelWriter wraps a SyslogWriter and call the right syslog level method matching the zerolog level.
type LogArrayMarshaler ¶
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 ¶
type LogObjectMarshaler interface {
MarshalZerologObject(e *Event)
}
LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface to be implemented by types used with Event/Context's Object methods.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
A Logger represents an active logging object that generates lines of JSON output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. There is no guarantee on access serialization to the Writer. If your Writer is not thread safe, you may consider a sync wrapper.
func Ctx ¶
Ctx returns the Logger associated with the ctx. If no logger is associated, DefaultContextLogger is returned, unless DefaultContextLogger is nil, in which case a disabled logger is returned.
func New ¶
New creates a root logger with given output writer. If the output writer implements the LevelWriter interface, the WriteLevel method will be called instead of the Write one.
Each logging operation makes a single call to the Writer's Write method. There is no guarantee on access serialization to the Writer. If your Writer is not thread safe, you may consider using sync wrapper.
Example ¶
package main import ( "os" "go.innotegrity.dev/zerolog" ) func main() { log := zerolog.New(os.Stdout) log.Info().Msg("hello world") }
Output: {"level":"info","message":"hello world"}
func (*Logger) Debug ¶
Debug starts a new message with debug level.
You must call Msg on the returned event in order to send the event.
Example ¶
package main import ( "os" "go.innotegrity.dev/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"}
func (*Logger) Err ¶
Err starts a new message with error level with err as a field if not nil or with info level if err is nil.
You must call Msg on the returned event in order to send the event.
func (*Logger) Error ¶
Error starts a new message with error level.
You must call Msg on the returned event in order to send the event.
Example ¶
package main import ( "errors" "os" "go.innotegrity.dev/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 (*Logger) Fatal ¶
Fatal starts a new message with fatal level. The os.Exit(1) function is called by the Msg method, which terminates the program immediately.
You must call Msg on the returned event in order to send the event.
func (Logger) Hook ¶
Hook returns a logger with the h Hook.
Example ¶
package main import ( "os" "go.innotegrity.dev/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).Hook(messageHook) log.Info().Msg("hello world") }
Output: {"level":"info","level_name":"info","the_message":"hello world","message":"hello world"}
func (*Logger) Info ¶
Info starts a new message with info level.
You must call Msg on the returned event in order to send the event.
Example ¶
package main import ( "os" "go.innotegrity.dev/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 (*Logger) InterceptLogrusMessages ¶
func (l *Logger) InterceptLogrusMessages(writer *io.PipeWriter)
InitLogrusInterceptor initializes the logrus global logger with an expected format so that they can be intercepted and parsed by ParseLogrusMessages.
func (*Logger) IsDebugEnabled ¶
IsDebugEnabled returns whether or not debug or trace logging is enabled.
func (Logger) Level ¶
Level creates a child logger with the minimum accepted level set to level.
Example ¶
package main import ( "os" "go.innotegrity.dev/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 (*Logger) Log ¶
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 ¶
package main import ( "os" "go.innotegrity.dev/zerolog" ) func main() { log := zerolog.New(os.Stdout) log.Log(). Str("foo", "bar"). Str("bar", "baz"). Msg("") }
Output: {"foo":"bar","bar":"baz"}
func (*Logger) Panic ¶
Panic starts a new message with panic level. The panic() function is called by the Msg method, which stops the ordinary flow of a goroutine.
You must call Msg on the returned event in order to send the event.
func (*Logger) ParseLogrusMessages ¶
func (l *Logger) ParseLogrusMessages(reader *io.PipeReader, handler ParseLogrusMessageErrorHandler)
ParseLogrusMessages uses a reader paired with the output writer from InitLogrusInterceptor to read messages from the pipe in a blocking manner until the writer is closed.
func (*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 ¶
package main import ( "os" "go.innotegrity.dev/zerolog" ) func main() { log := zerolog.New(os.Stdout) log.Print("hello world") }
Output: {"level":"debug","message":"hello world"}
func (*Logger) Printf ¶
Printf sends a log event using debug level and no extra field. Arguments are handled in the manner of fmt.Printf.
Example ¶
package main import ( "os" "go.innotegrity.dev/zerolog" ) func main() { log := zerolog.New(os.Stdout) log.Printf("hello %s", "world") }
Output: {"level":"debug","message":"hello world"}
func (Logger) Sample ¶
Sample returns a logger with the s sampler.
Example ¶
package main import ( "os" "go.innotegrity.dev/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 (*Logger) Trace ¶
Trace starts a new message with trace level.
You must call Msg on the returned event in order to send the event.
Example ¶
package main import ( "os" "go.innotegrity.dev/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 (*Logger) UpdateContext ¶
UpdateContext updates the internal logger's context.
Use this method with caution. If unsure, prefer the With method.
func (*Logger) Warn ¶
Warn starts a new message with warn level.
You must call Msg on the returned event in order to send the event.
Example ¶
package main import ( "os" "go.innotegrity.dev/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 (Logger) With ¶
With creates a child logger with the field added to its context.
Example ¶
package main import ( "os" "go.innotegrity.dev/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"}
func (Logger) WithContext ¶
WithContext returns a copy of ctx with the receiver attached. The Logger attached to the provided Context (if any) will not be effected. If the receiver's log level is Disabled it will only be attached to the returned Context if the provided Context has a previously attached Logger. If the provided Context has no attached Logger, a Disabled Logger will not be attached.
Note: to modify the existing Logger attached to a Context (instead of replacing it in a new Context), use UpdateContext with the following notation:
ctx := r.Context() l := zerolog.Ctx(ctx) l.UpdateContext(func(c Context) Context { return c.Str("bar", "baz") })
func (*Logger) WithLevel ¶
WithLevel starts a new message with level. Unlike Fatal and Panic methods, WithLevel does not terminate the program or stop the ordinary flow of a goroutine when used with their respective levels.
You must call Msg on the returned event in order to send the event.
Example ¶
package main import ( "os" "go.innotegrity.dev/zerolog" ) func main() { log := zerolog.New(os.Stdout) log.WithLevel(zerolog.InfoLevel). Msg("hello world") }
Output: {"level":"info","message":"hello world"}
func (*Logger) WouldLog ¶
WouldLog returns whether or not a mesage with the given level would be logged.
func (Logger) Write ¶
Write implements the io.Writer interface. This is useful to set as a writer for the standard library log.
Example ¶
package main import ( stdlog "log" "os" "go.innotegrity.dev/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 ParseLogrusMessageErrorHandler ¶
ParseLogrusMessageErrorHandler is called when an error occurs while parsing a logrus message.
type RandomSampler ¶
type RandomSampler uint32
RandomSampler use a PRNG to randomly sample an event out of N events, regardless of their level.
func (RandomSampler) Sample ¶
func (s RandomSampler) Sample(lvl Level) bool
Sample implements the Sampler interface.
type 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.
type SyslogWriter ¶
type SyslogWriter interface { io.Writer Debug(m string) error Info(m string) error Warning(m string) error Err(m string) error Emerg(m string) error Crit(m string) error }
SyslogWriter is an interface matching a syslog.Writer struct.
type TestWriter ¶
type TestWriter struct { T TestingLog // Frame skips caller frames to capture the original file and line numbers. Frame int }
TestWriter is a writer that writes to testing.TB.
func NewTestWriter ¶
func NewTestWriter(t TestingLog) TestWriter
NewTestWriter creates a writer that logs to the testing.TB.
type TestingLog ¶
type TestingLog interface { Log(args ...interface{}) Logf(format string, args ...interface{}) Helper() }
TestingLog is the logging interface of testing.TB.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
Package diode provides a thread-safe, lock-free, non-blocking io.Writer wrapper.
|
Package diode provides a thread-safe, lock-free, non-blocking io.Writer wrapper. |
Package hlog provides a set of http.Handler helpers for zerolog.
|
Package hlog provides a set of http.Handler helpers for zerolog. |
internal/mutil
Package mutil contains various functions that are helpful when writing http middleware.
|
Package mutil contains various functions that are helpful when writing http middleware. |
internal
|
|
cbor
Package cbor provides primitives for storing different data in the CBOR (binary) format.
|
Package cbor provides primitives for storing different data in the CBOR (binary) format. |
Package log provides a global logger for zerolog.
|
Package log provides a global logger for zerolog. |