How do I structure logs with fields using slog in Go?

In Go, the "slog" package provides a structured way to log messages with fields, enabling better monitoring and debugging of applications. This is achieved by adding key-value pairs to the log entries, which can contain contextual information about the logged events.

package main import ( "log/slog" "os" ) func main() { // Create a new logger logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) // Log a message with fields logger.Info("User logged in", "user_id", 42, "status", "success") // Log another message with different fields logger.Error("Failed to process order", "order_id", 1234, "error", "timeout") }

Go logging structured logging slog logging with fields Go log management Go programming