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

Integrating logging with context in Go using Zap is an efficient way to manage logs alongside context values. This integration allows developers to trace the flow of execution through various scopes easily. Using contexts helps in capturing additional metadata which can enhance logging outputs. Here is how to set it up:

First, make sure to import the necessary libraries:

import ( "context" "go.uber.org/zap" )

Then, create a logger and a new context with values:

func main() { logger, _ := zap.NewProduction() defer logger.Sync() // flushes buffer, if any ctx := context.WithValue(context.Background(), "request_id", "123456") logWithContext(ctx, logger) } func logWithContext(ctx context.Context, logger *zap.Logger) { requestID := ctx.Value("request_id").(string) logger.Info("Processing request", zap.String("request_id", requestID)) }

The above example demonstrates how to create a production logger, define a context with a request ID, and log that request ID in the logs. This method enriches the logs with context data, making it easier to track specific requests through your application.


Go logging Zap logging context in Go structured logging Go logging example