How do I integrate logging with context using zerolog in Go?

Integrate structured logging in Go applications using the zerolog library with context propagation.
logging, Go, zerolog, context, structured logging, Go applications

package main

import (
    "context"
    "github.com/rs/zerolog"
    "github.com/rs/zerolog/log"
    "os"
)

func main() {
    // Set up zerolog to log to standard output
    zerolog.ConsoleWriter := zerolog.NewConsoleWriter()
    log.Logger = log.Output(ConsoleWriter).With().Timestamp().Logger()

    // Create a root context
    ctx := context.Background()

    // Adding a logger to the context
    ctx = context.WithValue(ctx, "logger", log.With().Str("component", "main").Logger())

    // Use the logger from the context
    doWork(ctx)
}

func doWork(ctx context.Context) {
    // Retrieve the logger from the context
    logger := ctx.Value("logger").(zerolog.Logger)

    // Log an event
    logger.Info().Msg("Starting work...")

    // Simulating some work
    logger.Info().Msg("Work in progress...")
    
    // Indicate completion
    logger.Info().Msg("Work completed successfully.")
}
    

logging Go zerolog context structured logging Go applications