How to Use the slog Package for Structured Logging

Use the slog package to create structured, machine-readable logs in Go by initializing a handler and calling logger methods with key-value pairs.

The slog package provides structured logging by creating a logger that outputs key-value pairs in JSON or text format. Initialize a logger with slog.New and call methods like Info or Error to record events with context.

package main

import (
	"log/slog"
	"os"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	logger.Info("Server started", "port", 8080, "env", "production")
}