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")
}
Outputting JSON logs in Go for log aggregation sets up your application to print logs in a structured format instead of plain text. Log aggregation tools can easily parse these JSON lines to search, filter, and visualize your application's behavior. Think of it as writing a standardized report that a robot can read instantly, rather than a paragraph a human has to scan.