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")
}
Structured logging turns your application messages into a consistent, machine-readable format like JSON instead of plain text. This makes it much easier for automated tools to search, filter, and analyze your logs in production. Think of it as filling out a standardized form for every event instead of writing a free-form diary entry.