How to Use slog (Structured Logging) in Go 1.21+

Use the log/slog package to create a logger and output structured JSON logs with key-value pairs for better machine readability.

Use the log/slog package to create a logger and log structured messages with context. Import the package, create a logger instance, and call methods like Info, Debug, or Error with key-value pairs for structured data.

package main

import (
	"log/slog"
	"os"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	logger.Info("Application started", "version", "1.0", "env", "production")
}