How to Add Context to Log Messages in Go

Add context to Go log messages using context.WithValue or structured logging with log/slog for key-value pairs.

Add context to log messages in Go by using context.WithValue to attach data to the context and passing that context to your logging function.

ctx := context.WithValue(context.Background(), "user_id", 123)
log.Printf("%s: processing request", ctx.Value("user_id"))

Alternatively, use a structured logger like log/slog which natively supports key-value pairs for context:

ctx := context.Background()
logger := log.Default()
logger.InfoContext(ctx, "processing request", "user_id", 123)

For more complex scenarios, create a custom context key type to avoid collisions:

type contextKey string
const userKey contextKey = "user"

ctx := context.WithValue(context.Background(), userKey, 123)
log.Printf("%s: processing request", ctx.Value(userKey))