Set go Slog Levels With An Environment Variable
The examples in the slog docs are pretty convoluted. Setting a log level via an environment variable's actually
pretty simple. Here's the code. By default the code is silent, set LOG_LEVEL
in your environment to one of the strings "INFO", "DEBUG", "WARN" or "ERROR"
to enable that level of logging.
Note the function at the bottom called `getLogLevelFromEnv()` and that it's called in the HandlerOptions:
package main
import (
"log/slog"
"os"
"strings"
)
func main() {
opts := &slog.HandlerOptions{
Level : getLogLevelFromEnv(),
}
handler := slog.NewTextHandler(os.Stdout, opts)
logger := slog.New(handler)
logger.Debug("Debug message")
logger.Info("Info message")
logger.Warn("Warning message")
logger.Error("Error message")
// This message will not be logged since it's below the warning level
logger.Debug("This debug message will not be logged")
logger.Info("This info message will not be logged")
// These messages will be logged
logger.Warn("This is a warning message", "key", "value")
logger.Error("This is an error message", "key", "value")
}
func getLogLevelFromEnv() slog.Level {
levelStr := os.Getenv("LOG_LEVEL")
switch strings.ToLower(levelStr) {
case "debug":
return slog.LevelDebug
case "info":
return slog.LevelInfo
case "warn":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.Level(100) // Custom level higher than any standard level, so silent by default
}
}