### Install Zerolog Logger Source: https://github.com/rs/zerolog/blob/master/README.md Use this command to install the zerolog global logger package. ```bash go get -u github.com/rs/zerolog/log ``` -------------------------------- ### Logging Methods Source: https://github.com/rs/zerolog/wiki/coverage.html Methods for starting log events at different levels. ```APIDOC ## Trace ### Description Starts a new message with trace level. You must call `Msg` on the returned event to send the event. ### Method `func (l *Logger) Trace() *Event` ### Returns - *Event - An Event object to build and send a trace log message. ``` ```APIDOC ## Debug ### Description Starts a new message with debug level. You must call `Msg` on the returned event to send the event. ### Method `func (l *Logger) Debug() *Event` ### Returns - *Event - An Event object to build and send a debug log message. ``` ```APIDOC ## Info ### Description Starts a new message with info level. You must call `Msg` on the returned event to send the event. ### Method `func (l *Logger) Info() *Event` ### Returns - *Event - An Event object to build and send an info log message. ``` ```APIDOC ## Warn ### Description Starts a new message with warn level. You must call `Msg` on the returned event to send the event. ### Method `func (l *Logger) Warn() *Event` ### Returns - *Event - An Event object to build and send a warning log message. ``` ```APIDOC ## Error ### Description Starts a new message with error level. You must call `Msg` on the returned event to send the event. ### Method `func (l *Logger) Error() *Event` ### Returns - *Event - An Event object to build and send an error log message. ``` ```APIDOC ## Err ### Description Starts a new message with error level if the provided error is not nil, or with info level if the error is nil. You must call `Msg` on the returned event to send the event. ### Method `func (l *Logger) Err(err error) *Event` ### Parameters - **err** (error) - The error to log. ### Returns - *Event - An Event object to build and send the log message. ``` -------------------------------- ### Simple Logging Example with Zerolog Source: https://github.com/rs/zerolog/blob/master/README.md Demonstrates basic logging using the global zerolog logger. Ensure to set the time field format for efficiency. By default, logs are written to os.Stderr. ```go package main import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { // UNIX Time is faster and smaller than most timestamps zerolog.TimeFieldFormat = zerolog.TimeFormatUnix log.Print("hello world") } // Output: {"time":1516134303,"level":"debug","message":"hello world"} ``` -------------------------------- ### AppendArrayStart Source: https://github.com/rs/zerolog/wiki/coverage.html Appends an array start marker ('[') to the destination byte slice. ```APIDOC ## AppendArrayStart ### Description Appends markers to indicate the start of a JSON array ('[') to the destination byte slice. ### Method Signature func (Encoder) AppendArrayStart(dst []byte) []byte ### Parameters - **dst** ([]byte) - The destination byte slice to append to. ``` -------------------------------- ### Append Array Start Source: https://github.com/rs/zerolog/wiki/coverage.html Adds CBOR markers to indicate the start of an indefinite count array. ```Go // AppendArrayStart adds markers to indicate the start of an array. func (Encoder) AppendArrayStart(dst []byte) []byte { return append(dst, majorTypeArray|additionalTypeInfiniteCount) } ``` -------------------------------- ### HTTP Integration with alice and hlog Source: https://github.com/rs/zerolog/blob/master/README.md Integrates zerolog with `net/http` using the `hlog` package and `alice` middleware. This example sets up a logger, adds various request context fields, and logs incoming requests. ```go log := zerolog.New(os.Stdout).With(). Timestamp(). Str("role", "my-service"). Str("host", host). Logger() c := alice.New() // Install the logger handler with default output on the console c = c.Append(hlog.NewHandler(log)) // Install some provided extra handler to set some request's context fields. // Thanks to that handler, all our logs will come with some prepopulated fields. c = c.Append(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) { hlog.FromRequest(r).Info(). Str("method", r.Method). Stringer("url", r.URL). Int("status", status). Int("size", size). Dur("duration", duration). Msg("") })) c = c.Append(hlog.RemoteAddrHandler("ip")) c = c.Append(hlog.UserAgentHandler("user_agent")) c = c.Append(hlog.RefererHandler("referer")) c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id")) // Here is your final handler h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Get the logger from the request's context. You can safely assume it // will be always there: if the handler is removed, hlog.FromRequest // will return a no-op logger. hlog.FromRequest(r).Info(). Str("user", "current user"). Str("status", "ok"). Msg("Something happened") // Output: {"level":"info","time":"2001-02-03T04:05:06Z","role":"my-service","host":"local-hostname","req_id":"b4g0l5t6tfid6dtrapu0","user":"current user","status":"ok","message":"Something happened"} })) http.Handle("/", h) if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal().Err(err).Msg("Startup failed") } ``` -------------------------------- ### Append Array Start Marker Source: https://github.com/rs/zerolog/wiki/coverage.html Appends the opening square bracket '[' to indicate the start of a JSON array. ```Go // AppendArrayStart adds markers to indicate the start of an array. func (Encoder) AppendArrayStart(dst []byte) []byte { return append(dst, '[') } ``` -------------------------------- ### Append Begin Marker Source: https://github.com/rs/zerolog/wiki/coverage.html Inserts a CBOR map start marker into the destination byte array, indicating an indefinite count map. ```Go // AppendBeginMarker inserts a map start into the dst byte array. func (Encoder) AppendBeginMarker(dst []byte) []byte { return append(dst, majorTypeMap|additionalTypeInfiniteCount) } ``` -------------------------------- ### AppendBeginMarker Source: https://github.com/rs/zerolog/wiki/coverage.html Appends a map start marker ('{') to the destination byte slice. ```APIDOC ## AppendBeginMarker ### Description Appends a map start marker ('{') to the destination byte slice. ### Method Signature func (Encoder) AppendBeginMarker(dst []byte) []byte ### Parameters - **dst** ([]byte) - The destination byte slice to append to. ``` -------------------------------- ### Start Error or Info Level Message with Error Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event at the Error level if an error is provided, otherwise starts at the Info level. The error is included as a field if not nil. The Msg method must be called on the returned event to send the log. ```go // 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) Err(err error) *Event { if err != nil { return l.Error().Err(err) } return l.Info() } ``` -------------------------------- ### Start Info Level Message Source: https://github.com/rs/zerolog/wiki/coverage.html Initiates a new log event at the Info level. The Msg method must be called on the returned event to send the log. ```go // Info starts a new message with info level. // // You must call Msg on the returned event in order to send the event. func (l *Logger) Info() *Event { return l.newEvent(InfoLevel, nil) } ``` -------------------------------- ### Log Info Event Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event with info level. The message is sent when Msg is called on the returned event. ```go // Info starts a new message with info level. // // You must call Msg on the returned event in order to send the event. func Info() *zerolog.Event { return Logger.Info() } ``` -------------------------------- ### Append Map Start Marker Source: https://github.com/rs/zerolog/wiki/coverage.html Appends the opening curly brace '{' to indicate the start of a JSON object. ```Go // AppendBeginMarker inserts a map start into the dst byte array. func (Encoder) AppendBeginMarker(dst []byte) []byte { return append(dst, '{') } ``` -------------------------------- ### Log level methods in zerolog Source: https://context7.com/rs/zerolog/llms.txt Use methods like Trace(), Debug(), Info(), Warn(), Error() to start events at specific levels. Fatal() exits the program, Panic() panics. Chain fields and finalize with Msg() or Msgf(). ```go package main import ( "errors" "os" "github.com/rs/zerolog" ) func main() { log := zerolog.New(os.Stdout).With().Timestamp().Logger() log.Trace().Str("detail", "verbose").Msg("trace event") // {"level":"trace","detail":"verbose","time":"...","message":"trace event"} log.Debug().Int("attempt", 1).Msg("retrying connection") // {"level":"debug","attempt":1,"time":"...","message":"retrying connection"} log.Info().Str("user", "alice").Msg("login successful") // {"level":"info","user":"alice","time":"...","message":"login successful"} log.Warn().Dur("lag", 2500*1e6).Msg("high latency detected") // {"level":"warn","lag":2500,"time":"...","message":"high latency detected"} err := errors.New("connection refused") log.Error().Err(err).Str("host", "db.internal").Msg("database unreachable") // {"level":"error","error":"connection refused","host":"db.internal","time":"...","message":"database unreachable"} // log.Fatal().Msg("...") // writes then calls os.Exit(1) // log.Panic().Msg("...") // writes then calls panic(msg) } ``` -------------------------------- ### Start Warn Level Message Source: https://github.com/rs/zerolog/wiki/coverage.html Initiates a new log event at the Warn level. The Msg method must be called on the returned event to send the log. ```go // Warn starts a new message with warn level. // // You must call Msg on the returned event in order to send the event. func (l *Logger) Warn() *Event { return l.newEvent(WarnLevel, nil) } ``` -------------------------------- ### IP Prefix Test Cases Source: https://github.com/rs/zerolog/wiki/coverage.html Contains test cases for encoding and decoding IP network prefixes (CIDR notation). Includes IPv4 and IPv6 examples with their binary and text representations. ```go var IPPrefixTestCases = []struct { Pfx net.IPNet Text string // ASCII representation of pfx Binary string // CBOR representation of pfx }{ {net.IPNet{IP: net.IP{0, 0, 0, 0}, Mask: net.CIDRMask(0, 32)}, "\"0.0.0.0/0\"", "\xd9\x01\x05\xa1\x44\x00\x00\x00\x00\x00"}, {net.IPNet{IP: net.IP{192, 168, 0, 100}, Mask: net.CIDRMask(24, 32)}, "\"192.168.0.100/24\"", "\xd9\x01\x05\xa1\x44\xc0\xa8\x00\x64\x18\x18"}, {net.IPNet{IP: net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, Mask: net.CIDRMask(128, 128)}, "\"::1/128\"", "\xd9\x01\x05\xa1\x50\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x18\x80"}, } ``` -------------------------------- ### Start Trace Level Message Source: https://github.com/rs/zerolog/wiki/coverage.html Initiates a new log event at the Trace level. The Msg method must be called on the returned event to send the log. ```go // Trace starts a new message with trace level. // // You must call Msg on the returned event in order to send the event. func (l *Logger) Trace() *Event { return l.newEvent(TraceLevel, nil) } ``` -------------------------------- ### Zerolog Field Duplication Example Source: https://github.com/rs/zerolog/blob/master/README.md Demonstrates how Zerolog handles duplicate keys in log messages. Note that Zerolog does not perform de-duplication, resulting in multiple keys with the same name in the final JSON output. Consumers may interpret the last value, but this is not guaranteed. ```go logger := zerolog.New(os.Stderr).With().Timestamp().Logger() logger.Info(). Timestamp(). Msg("dup") // Output: {"level":"info","time":1494567715,"time":1494567715,"message":"dup"} ``` -------------------------------- ### Create a Random Sampler in Go Source: https://github.com/rs/zerolog/wiki/coverage.html Use RandomSampler to sample log events at a specified frequency. For example, RandomSampler(10) samples approximately 1 in every 10 events. ```go package zerolog import ( "math/rand" "sync/atomic" "time" ) 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) ) // Sampler defines an interface to a log sampler. type Sampler interface { // Sample returns true if the event should be part of the sample, false if // the event should be dropped. Sample(lvl Level) bool } // RandomSampler use a PRNG to randomly sample an event out of N events, // regardless of their level. type RandomSampler uint32 // Sample implements the Sampler interface. func (s RandomSampler) Sample(lvl Level) bool { if s <= 0 { return false } if rand.Intn(int(s)) != 0 { return false } return true } ``` -------------------------------- ### Implement Fatal Event Logging in Zerolog Source: https://github.com/rs/zerolog/wiki/coverage.html The Fatal method starts a new log event with FatalLevel. It includes logic to close the writer if it implements io.Closer and then either calls FatalExitFunc if set, or os.Exit(1) as a default behavior to terminate the program. You must call Msg on the returned event to send it. ```go func (l *Logger) Fatal() *Event { return l.newEvent(FatalLevel, func(msg string) { if closer, ok := l.w.(io.Closer); ok { // Close the writer to flush any buffered message. Otherwise the message // could be lost if FatalExitFunc() terminates the program immediately or // os.Exit(1) is called if not FatalExitFunc isn't set (default). closer.Close() } if FatalExitFunc != nil { FatalExitFunc() } else { os.Exit(1) // untestable: terminates the program, cannot be covered } }) } ``` -------------------------------- ### Simple Leveled Logging with Zerolog Source: https://github.com/rs/zerolog/blob/master/README.md Demonstrates logging at the 'info' level using zerolog. Remember that the log chain must conclude with a Msg or Msgf method call to ensure the log event is written. ```go package main import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { zerolog.TimeFieldFormat = zerolog.TimeFormatUnix log.Info().Msg("hello world") } // Output: {"time":1516134303,"level":"info","message":"hello world"} ``` -------------------------------- ### Implement Panic Event Logging in Zerolog Source: https://github.com/rs/zerolog/wiki/coverage.html The Panic method starts a new log event with PanicLevel. 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 to send it. ```go // 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) Panic() *Event { return l.newEvent(PanicLevel, func(msg string) { panic(msg) }) } ``` -------------------------------- ### Create Custom Logger Instance Source: https://github.com/rs/zerolog/blob/master/README.md Demonstrates creating a custom logger instance with specific configurations, such as including timestamps, and then using it to log messages. ```go logger := zerolog.New(os.Stderr).With().Timestamp().Logger() logger.Info().Str("foo", "bar").Msg("hello world") ``` ```text // Output: {"level":"info","time":1494567715,"message":"hello world","foo":"bar"} ``` -------------------------------- ### Create a logger with zerolog.New Source: https://context7.com/rs/zerolog/llms.txt Create a root logger writing to an io.Writer. Use With().Timestamp() to include timestamps. Log events by chaining methods like Info(), Error() and finalizing with Msg(). ```go package main import ( "os" "github.com/rs/zerolog" ) func main() { logger := zerolog.New(os.Stderr).With().Timestamp().Logger() logger.Info(). Str("service", "api-gateway"). Int("port", 8080). Msg("server started") // Output: {"level":"info","service":"api-gateway","port":8080,"time":"2024-01-15T10:00:00Z","message":"server started"} logger.Error(). Str("path", "/users"). Int("status", 500). Msg("request failed") // Output: {"level":"error","path":"/users","status":500,"time":"2024-01-15T10:00:01Z","message":"request failed"} } ``` -------------------------------- ### Create Logger Instance Source: https://github.com/rs/zerolog/wiki/coverage.html Illustrates creating a logger instance with a specific output and timestamp enabled. ```go 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"} ``` -------------------------------- ### Add Time Difference to Event Source: https://github.com/rs/zerolog/wiki/coverage.html Adds the duration between two times (t and start) as a field. If t is not after start, duration is 0. Format follows Dur(). ```go // TimeDiff adds the field key with positive duration between time t and start. // If time t is not greater than start, duration will be 0. // Duration format follows the same principle as Dur(). func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event { if e == nil { return e } var d time.Duration if t.After(start) { d = t.Sub(start) } e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldFormat, DurationFieldInteger, FloatingPointPrecision) return e } ``` -------------------------------- ### Write Zerolog Array to Destination Source: https://github.com/rs/zerolog/wiki/coverage.html Appends the Array's content to a destination byte slice, formatting it as a JSON array. It starts with an array start marker, appends the buffer content if any, and ends with an array end marker before returning the modified slice and recycling the Array object. ```go func (a *Array) write(dst []byte) []byte { dst = enc.AppendArrayStart(dst) if len(a.buf) > 0 { dst = append(dst, a.buf...) } dst = enc.AppendArrayEnd(dst) putArray(a) return dst } ``` -------------------------------- ### Implement a Basic Sampler in Go Source: https://github.com/rs/zerolog/wiki/coverage.html BasicSampler sends every Nth event, regardless of its log level. It uses an atomic counter to track events. ```go package zerolog import ( "math/rand" "sync/atomic" "time" ) // BasicSampler is a sampler that will send every Nth events, regardless of // their level. type BasicSampler struct { N uint32 counter uint32 } // Sample implements the Sampler interface. func (s *BasicSampler) Sample(lvl Level) bool { n := s.N if n == 0 { return false } if n == 1 { return true } c := atomic.AddUint32(&s.counter, 1) return c%n == 1 } ``` -------------------------------- ### Implement Log Sampling with BasicSampler Source: https://context7.com/rs/zerolog/llms.txt Control the volume of logs by sampling events. BasicSampler logs every Nth event, useful for reducing noise in high-frequency logs. ```go package main import ( "os" "time" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { // Log every 100th debug event, all others pass through sampledLog := log.Logger.Sample(zerolog.LevelSampler{ DebugSampler: &zerolog.BurstSampler{ Burst: 5, Period: 1 * time.Second, NextSampler: &zerolog.BasicSampler{N: 100}, }, }) for i := 0; i < 1000; i++ { sampledLog.Debug().Int("i", i).Msg("tick") // Only first 5 per second, then 1-in-100 are logged } // Simple: log every 10th event regardless of level _ = zerolog.New(os.Stdout).Sample(&zerolog.BasicSampler{N: 10}) } ``` -------------------------------- ### Initialize Zerolog Logger Source: https://github.com/rs/zerolog/wiki/coverage.html Creates a new root logger with the specified output writer. If the writer implements LevelWriter, WriteLevel is used; otherwise, a LevelWriterAdapter is employed. Defaults to io.Discard if the writer is nil. ```go func New(w io.Writer) Logger { if w == nil { w = io.Discard } lw, ok := w.(LevelWriter) if !ok { lw = LevelWriterAdapter{w} } return Logger{w: lw, level: TraceLevel} } ``` -------------------------------- ### Basic Info Log Source: https://github.com/rs/zerolog/wiki/coverage.html Demonstrates a simple info log message with the global logger. ```go import "github.com/rs/zerolog/log" log.Info().Msg("hello world") // Output: {"time":1494567715,"level":"info","message":"hello world"} ``` -------------------------------- ### AppendArrayStart Source: https://github.com/rs/zerolog/wiki/coverage.html Appends CBOR markers to indicate the start of an array with an indefinite length. ```APIDOC ## AppendArrayStart ### Description Appends CBOR markers to indicate the start of an array with an indefinite length. ### Method func (Encoder) AppendArrayStart(dst []byte) []byte ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **dst** ([]byte) - The byte array with the appended array start markers. #### Response Example None ``` -------------------------------- ### Enable Pretty Console Logging Source: https://github.com/rs/zerolog/blob/master/README.md Configure Zerolog to output human-friendly, colorized logs to the console using `zerolog.ConsoleWriter`. This is ideal for development environments. ```go log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) log.Info().Str("foo", "bar").Msg("Hello world") // Output: 3:04PM INF Hello World foo=bar ``` -------------------------------- ### Get Global Log Level Source: https://github.com/rs/zerolog/wiki/coverage.html Returns the current global log level. ```go func GlobalLevel() Level { return Level(atomic.LoadInt32(gLevel)) } ``` -------------------------------- ### Initialize ConsoleWriter in Go Source: https://github.com/rs/zerolog/wiki/coverage.html Creates a new ConsoleWriter with default settings or custom options. It handles colorization on Windows for standard output and error streams. ```go func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter { w := ConsoleWriter{ Out: os.Stdout, TimeFormat: consoleDefaultTimeFormat, PartsOrder: consoleDefaultPartsOrder(), } for _, opt := range options { opt(&w) } // Fix color on Windows if w.Out == os.Stdout || w.Out == os.Stderr { w.Out = colorable.NewColorable(w.Out.(*os.File)) } return w } ``` -------------------------------- ### Get Current Log Level Source: https://github.com/rs/zerolog/wiki/coverage.html Retrieves the current minimum log level configured for the logger instance. ```go // GetLevel returns the current Level of l. func (l Logger) GetLevel() Level { return l.level } ``` -------------------------------- ### AppendBeginMarker Source: https://github.com/rs/zerolog/wiki/coverage.html Appends a CBOR map start marker to the destination byte array, indicating an indefinite length map. ```APIDOC ## AppendBeginMarker ### Description Appends a CBOR map start marker to the destination byte array, indicating an indefinite length map. ### Method func (Encoder) AppendBeginMarker(dst []byte) []byte ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **dst** ([]byte) - The byte array with the appended map start marker. #### Response Example None ``` -------------------------------- ### Sampled Logging Source: https://github.com/rs/zerolog/wiki/coverage.html Demonstrates how to use sampling to log messages at a specific frequency. ```go sampled := log.Sample(&zerolog.BasicSampler{N: 10}) sampled.Info().Msg("will be logged every 10 messages") ``` -------------------------------- ### Context Integration: Attach and Retrieve Logger Source: https://github.com/rs/zerolog/blob/master/README.md Demonstrates attaching a zerolog `Logger` to a `context.Context` using `WithContext` and retrieving it with `Ctx`. If the logger is not found in the context, a default or disabled logger is returned. ```go func f() { logger := zerolog.New(os.Stdout) ctx := context.Background() // Attach the Logger to the context.Context ctx = logger.WithContext(ctx) someFunc(ctx) } func someFunc(ctx context.Context) { // Get Logger from the go Context. if it's nil, then // `zerolog.DefaultContextLogger` is returned, if // `DefaultContextLogger` is nil, then a disabled logger is returned. logger := zerolog.Ctx(ctx) logger.Info().Msg("Hello") } ``` -------------------------------- ### Get Logger from Context Source: https://github.com/rs/zerolog/wiki/coverage.html Retrieves the zerolog.Logger associated with the given context. If no logger is found, a disabled logger is returned. ```go // Ctx returns the Logger associated with the ctx. If no logger // is associated, a disabled logger is returned. func Ctx(ctx context.Context) *zerolog.Logger { return zerolog.Ctx(ctx) } ``` -------------------------------- ### Main Function for Log Generation Source: https://github.com/rs/zerolog/wiki/coverage.html Parses command-line flags for output file, number of logs, and compression, then calls the writeLog function. This is the entry point for the logging application. ```go func main() { outFile := flag.String("out", "", "Output File to which logs will be written to (WILL overwrite if already present).") numLogs := flag.Int("num", 10, "Number of log messages to generate.") doCompress := flag.Bool("compress", false, "Enable inline compressed writer") flag.Parse() writeLog(*outFile, *numLogs, *doCompress) } ``` -------------------------------- ### AppendKey Source: https://github.com/rs/zerolog/wiki/coverage.html Appends a new key to the output JSON. It handles adding a comma separator if the destination is not starting with an opening brace. ```APIDOC ## AppendKey ### Description Appends a new key to the output JSON. It handles adding a comma separator if the destination is not starting with an opening brace. ### Method func (e Encoder) AppendKey(dst []byte, key string) []byte ### Parameters - **dst** ([]byte) - The destination byte slice to append to. - **key** (string) - The key to append. ### Returns - ([]byte) - The updated destination byte slice with the appended key and a colon. ``` -------------------------------- ### Log Warn Event Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event with warn level. The message is sent when Msg is called on the returned event. ```go // Warn starts a new message with warn level. // // You must call Msg on the returned event in order to send the event. func Warn() *zerolog.Event { return Logger.Warn() } ``` -------------------------------- ### Waiter Configuration Options Source: https://github.com/rs/zerolog/wiki/coverage.html Provides configuration options for the Waiter, specifically setting the context. ```go type WaiterConfigOption func(*Waiter) func WithWaiterContext(ctx context.Context) WaiterConfigOption { return func(c *Waiter) { c.ctx = ctx } } ``` -------------------------------- ### Configure Zerolog Console Writer with Time Format Source: https://github.com/rs/zerolog/wiki/coverage.html Sets up a Zerolog console writer with a customizable time format based on command-line flags. ```go func main() { timeFormats := map[string]string{ "default": time.Kitchen, "full": time.RFC1123, } timeFormatFlag := flag.String( "time-format", "default", "Time format, either 'default' or 'full'", ) flag.Parse() timeFormat, ok := timeFormats[*timeFormatFlag] if !ok { panic("Invalid time-format provided") } writer := zerolog.NewConsoleWriter() writer.TimeFormat = timeFormat if isInputFromPipe() { _ = processInput(os.Stdin, writer) } else if flag.NArg() >= 1 { for _, filename := range flag.Args() { // Scan each line from filename and write it into writer reader, err := os.Open(filename) if err != nil { fmt.Printf("%s open: %v", filename, err) os.Exit(1) } if err := processInput(reader, writer); err != nil { fmt.Printf("%s scan: %v", filename, err) os.Exit(1) } } } else { fmt.Println("Usage:") fmt.Println(" app_with_zerolog | 2> >(prettylog)") fmt.Println(" prettylog zerolog_output.jsonl") os.Exit(1) return } } ``` -------------------------------- ### Log Debug Event Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event with debug level. The message is sent when Msg is called on the returned event. ```go // Debug starts a new message with debug level. // // You must call Msg on the returned event in order to send the event. func Debug() *zerolog.Event { return Logger.Debug() } ``` -------------------------------- ### Log with Fields Source: https://github.com/rs/zerolog/wiki/coverage.html Shows how to add fields to log messages using the global logger. ```go log.Info().Str("foo", "bar").Msg("hello world") // Output: {"time":1494567715,"level":"info","message":"hello world","foo":"bar"} ``` -------------------------------- ### Log Trace Event Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event with trace level. The message is sent when Msg is called on the returned event. ```go // Trace starts a new message with trace level. // // You must call Msg on the returned event in order to send the event. func Trace() *zerolog.Event { return Logger.Trace() } ``` -------------------------------- ### Log with Contextual Hooks Source: https://github.com/rs/zerolog/wiki/coverage.html Shows how to implement and use custom hooks to add contextual information to log events. ```go // 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("") ``` -------------------------------- ### Get Logger from Request Context Source: https://github.com/rs/zerolog/wiki/coverage.html Retrieves the zerolog logger instance from the request's context. This is a convenient shortcut for `log.Ctx(r.Context())`. ```go func FromRequest(r *http.Request) *zerolog.Logger { return log.Ctx(r.Context()) } ``` -------------------------------- ### Run PrettyLog with Go Run on Windows Source: https://github.com/rs/zerolog/blob/master/cmd/prettylog/README.md Redirect stderr to stdout and then pipe it to the prettylog script using `go run` on Windows. ```shell some_program_with_zerolog 2>&1 | go run cmd/prettylog/prettylog.go ``` -------------------------------- ### Log Event with No Level Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event without a predefined level. Events are still disabled if zerolog.GlobalLevel is set to zerolog.Disabled. ```go // Log starts a new message with no level. Setting zerolog.GlobalLevel to // zerolog.Disabled will still disable events produced by this method. // // You must call Msg on the returned event in order to send the event. func Log() *zerolog.Event { return Logger.Log() } ``` -------------------------------- ### Sub-logger with Context Source: https://github.com/rs/zerolog/wiki/coverage.html Demonstrates creating a sub-logger with additional context fields. ```go sublogger := log.With().Str("component", "foo").Logger() sublogger.Info().Msg("hello world") // Output: {"time":1494567715,"level":"info","message":"hello world","component":"foo"} ``` -------------------------------- ### Log Error Event (Explicit) Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event with error level. The message is sent when Msg is called on the returned event. ```go // Error starts a new message with error level. // // You must call Msg on the returned event in order to send the event. func Error() *zerolog.Event { return Logger.Error() } ``` -------------------------------- ### Contextual Logging with Zerolog Source: https://github.com/rs/zerolog/blob/master/README.md Shows how to add contextual key:value pairs to log messages for richer debugging information. Fields are strongly typed. The chain must end with a Msg or Msgf call. ```go package main import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { zerolog.TimeFieldFormat = zerolog.TimeFormatUnix log.Debug(). Str("Scale", "833 cents"). Float64("Interval", 833.09). Msg("Fibonacci is everywhere") log.Debug(). Str("Name", "Tom"). Send() } // Output: {"level":"debug","Scale":"833 cents","Interval":833.09,"time":1562212768,"message":"Fibonacci is everywhere"} // Output: {"level":"debug","Name":"Tom","time":1562212768} ``` -------------------------------- ### Log Event with Specific Level Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event with a dynamically specified level. The message is sent when Msg is called on the returned event. ```go // WithLevel starts a new message with level. // // You must call Msg on the returned event in order to send the event. func WithLevel(level zerolog.Level) *zerolog.Event { return Logger.WithLevel(level) } ``` -------------------------------- ### Log Panic Event Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event with panic level. The Msg method will call the panic function. Use this for unrecoverable errors. ```go // Panic starts a new message with panic level. The message is also sent // to the panic function. // // You must call Msg on the returned event in order to send the event. func Panic() *zerolog.Event { return Logger.Panic() } ``` -------------------------------- ### Unsigned Integer Test Cases for Zerolog Source: https://github.com/rs/zerolog/wiki/coverage.html Provides test cases for unsigned integers, including specific values and standard unsigned integer constants. ```go type UnsignedIntTestCase struct { Val uint Binary string Bigbinary string } var AdditionalUnsignedIntegerTestCases = []UnsignedIntTestCase{ {0x7FFFFFFF, "\x18\xff", "\x1a\x7f\xff\xff\xff"}, {0x80000000, "\x19\xff\xff", "\x1a\x80\x00\x00\x00"}, {1000000, "\x1b\x80\x00\x00\x00\x00\x00\x00\x00", "\x1a\x00\x0f\x42\x40"}, //Constants {math.MaxUint8, "\x18\xff", "\x18\xff"}, {math.MaxUint16, "\x19\xff\xff", "\x19\xff\xff"}, {math.MaxUint32, "\x1a\xff\xff\xff\xff", "\x1a\xff\xff\xff\xff"}, {math.MaxUint64, "\x1b\xff\xff\xff\xff\xff\xff\xff\xff", "\x1b\xff\xff\xff\xff\xff\xff\xff\xff"}, } ``` ```go func unsignedIntegerTestCases() []UnsignedIntTestCase { size := len(IntegerTestCases) + len(AdditionalUnsignedIntegerTestCases) cases := make([]UnsignedIntTestCase, 0, size) cases = append(cases, AdditionalUnsignedIntegerTestCases...) for _, itc := range IntegerTestCases { if itc.Val < 0 { continue } cases = append(cases, UnsignedIntTestCase{Val: uint(itc.Val), Binary: itc.Binary, Bigbinary: itc.Binary}) } return cases } var UnsignedIntegerTestCases = unsignedIntegerTestCases() ``` -------------------------------- ### Log Fatal Event Source: https://github.com/rs/zerolog/wiki/coverage.html Starts a new log event with fatal level. The Msg method will call os.Exit(1). Use this for critical errors. ```go // Fatal starts a new message with fatal level. The os.Exit(1) function // is called by the Msg method. // // You must call Msg on the returned event in order to send the event. func Fatal() *zerolog.Event { return Logger.Fatal() } ``` -------------------------------- ### Log without Level or Message Source: https://github.com/rs/zerolog/blob/master/README.md Shows how to use the `Log` method for logging without a specific level and how to log an empty message using `Msg("")`. ```go package main import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { zerolog.TimeFieldFormat = zerolog.TimeFormatUnix log.Log(). Str("foo", "bar"). Msg("") } ``` ```text // Output: {"time":1494567715,"foo":"bar"} ``` -------------------------------- ### Start Fatal Level Message Source: https://github.com/rs/zerolog/wiki/coverage.html Initiates a new log event at the Fatal level. The FatalExitFunc is called by the Msg method, which by default terminates the program. ```go // Fatal starts a new message with fatal level. The FatalExitFunc interceptor function // is called by the Msg method, which by default terminates the program immediately ``` -------------------------------- ### Run Zerolog Linter via Go Run Source: https://github.com/rs/zerolog/blob/master/cmd/lint/README.md Execute the zerolog linter directly using the `go run` command. Specify the package to inspect as the primary argument. ```bash go run cmd/lint/lint.go ``` -------------------------------- ### MAC Address Test Cases Source: https://github.com/rs/zerolog/wiki/coverage.html Specifies test cases for encoding and decoding MAC addresses. Includes examples with their ASCII and CBOR binary representations. ```go var MacAddrTestCases = []struct { Macaddr net.HardwareAddr Text string // ASCII representation of macaddr Binary string // CBOR representation of macaddr }{ {net.HardwareAddr{0x12, 0x34, 0x56, 0x78, 0x90, 0xab}, "\"12:34:56:78:90:ab\"", "\xd9\x01\x04\x46\x12\x34\x56\x78\x90\xab"}, {net.HardwareAddr{0x20, 0x01, 0x0d, 0xb8, 0x85, 0xa3}, "\"20:01:0d:b8:85:a3\"", "\xd9\x01\x04\x46\x20\x01\x0d\xb8\x85\xa3"}, } ``` -------------------------------- ### Initialize Global Zerolog Logger Source: https://github.com/rs/zerolog/wiki/coverage.html Sets up the global zerolog logger to write to standard error with timestamps. This is the default logger instance used by the package. ```go package log import ( "os" "github.com/rs/zerolog" ) // Logger is the global logger. var Logger = zerolog.New(os.Stderr).With().Timestamp().Logger() ``` -------------------------------- ### Start Error Level Message Source: https://github.com/rs/zerolog/wiki/coverage.html Initiates a new log event at the Error level. The Msg method must be called on the returned event to send the log. ```go // Error starts a new message with error level. // // You must call Msg on the returned event in order to send the event. func (l *Logger) Error() *Event { return l.newEvent(ErrorLevel, nil) } ``` -------------------------------- ### Logger Initialization Source: https://github.com/rs/zerolog/wiki/coverage.html Provides methods for creating and configuring a zerolog Logger instance. ```APIDOC ## New Logger ### Description Creates a root logger with the 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 a sync wrapper. ### Function Signature `func New(w io.Writer) Logger` ### Parameters - **w** (io.Writer) - The output writer for the logger. ### Returns - Logger - A new zerolog Logger instance. ``` ```APIDOC ## Nop Logger ### Description Returns a disabled logger for which all operations are no-op. ### Function Signature `func Nop() Logger` ### Returns - Logger - A disabled zerolog Logger instance. ``` -------------------------------- ### Start Debug Level Message Source: https://github.com/rs/zerolog/wiki/coverage.html Initiates a new log event at the Debug level. The Msg method must be called on the returned event to send the log. ```go // Debug starts a new message with debug level. // // You must call Msg on the returned event in order to send the event. func (l *Logger) Debug() *Event { return l.newEvent(DebugLevel, nil) } ``` -------------------------------- ### Basic Log Sampling Source: https://github.com/rs/zerolog/blob/master/README.md Implement basic log sampling to control the frequency of log messages. `zerolog.BasicSampler` logs one message every N messages. ```go sampled := log.Sample(&zerolog.BasicSampler{N: 10}) sampled.Info().Msg("will be logged every 10 messages") // Output: {"time":1494567715,"level":"info","message":"will be logged every 10 messages"} ``` -------------------------------- ### Use Global Zerolog Logger Source: https://context7.com/rs/zerolog/llms.txt Utilize the global logger from the zerolog/log sub-package for convenient logging. The global logger can be replaced and its level can be set. ```go package main import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { // Replace global logger log.Logger = log.Logger.With().Str("app", "myservice").Logger() log.Info().Str("event", "startup").Msg("application started") // {"level":"info","app":"myservice","event":"startup","time":"...","message":"application started"} log.Warn().Int("goroutines", 1024).Msg("high goroutine count") // {"level":"warn","app":"myservice","goroutines":1024,"time":"...","message":"high goroutine count"} zerolog.SetGlobalLevel(zerolog.ErrorLevel) log.Info().Msg("this is suppressed") // filtered out log.Error().Msg("this still appears") // {"level":"error","app":"myservice","time":"...","message":"this still appears"} } ``` -------------------------------- ### AppendInts64 to Byte Slice Source: https://github.com/rs/zerolog/wiki/coverage.html Encodes and inserts an array of int64 values into the destination byte array. Handles empty arrays by appending start and end markers. ```go func (e Encoder) AppendInts64(dst []byte, vals []int64) []byte { major := majorTypeArray l := len(vals) if l == 0 { return e.AppendArrayEnd(e.AppendArrayStart(dst)) } if l <= additionalMax { lb := byte(l) dst = append(dst, major|lb) } else { dst = appendCborTypePrefix(dst, major, uint64(l)) } for _, v := range vals { dst = e.AppendInt64(dst, v) } return dst } ``` -------------------------------- ### Log Errors with Stacktrace Source: https://github.com/rs/zerolog/blob/master/README.md Illustrates how to add a formatted stacktrace to errors using `github.com/pkg/errors` and configuring `zerolog.ErrorStackMarshaler`. The stacktrace is only included if `zerolog.ErrorStackMarshaler` is set. ```go package main import ( "github.com/pkg/errors" "github.com/rs/zerolog/pkgerrors" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { zerolog.TimeFieldFormat = zerolog.TimeFormatUnix zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack err := outer() log.Error().Stack().Err(err).Msg("") } func inner() error { return errors.New("seems we have an error here") } func middle() error { err := inner() if err != nil { return err } return nil } func outer() error { err := middle() if err != nil { return err } return nil } ``` ```text // Output: {"level":"error","stack":[{"func":"inner","line":"20","source":"errors.go"},{"func":"middle","line":"24","source":"errors.go"},{"func":"outer","line":"32","source":"errors.go"},{"func":"main","line":"15","source":"errors.go"},{"func":"main","line":"204","source":"proc.go"},{"func":"goexit","line":"1374","source":"asm_amd64.s"}],"error":"seems we have an error here","time":1609086683} ```