How to Output JSON Logs in Go for Log Aggregation

Output JSON logs in Go by creating a logger with slog.NewJSONHandler and writing to os.Stdout.

Use the log/slog package with slog.NewJSONHandler to output structured JSON logs. This handler formats log records as JSON, making them machine-readable for aggregation tools like Elasticsearch or Splunk.

package main

import (
	"log/slog"
	"os"
)

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