How to Implement Log Levels in Go

Implement log levels in Go using the standard library's slog package by configuring a Handler with a specific Level threshold.

Go does not have built-in log levels; you must use the log package with a custom Writer or a third-party library like slog (Go 1.21+) to filter output by severity.

package main

import (
	"log/slog"
	"os"
)

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo, // Filter: Debug, Info, Warn, Error
	}))
	logger.Debug("This is hidden")
	logger.Info("This is visible")
	logger.Error("This is visible")
}