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")
}
The slog package lets your Go programs write logs that are easy for computers to read and analyze, unlike plain text. Instead of writing messy sentences, it records data as neat labels and values, like a spreadsheet row. This helps you quickly search for specific errors or track performance metrics in large systems.