43 lines
1.2 KiB
Go
43 lines
1.2 KiB
Go
|
|
package logger
|
||
|
|
|
||
|
|
import (
|
||
|
|
"log/slog"
|
||
|
|
"os"
|
||
|
|
)
|
||
|
|
|
||
|
|
// LoggerLevel expresses the desired logging verbosity. Unlike a full log-level
|
||
|
|
// enum, it only distinguishes between a verbose development mode and a quieter
|
||
|
|
// production mode; it is converted to an slog.Level by New.
|
||
|
|
type LoggerLevel int
|
||
|
|
|
||
|
|
const (
|
||
|
|
// Development enables debug-level output, suitable for local development.
|
||
|
|
Development LoggerLevel = iota
|
||
|
|
// Production limits output to info level and above.
|
||
|
|
Production
|
||
|
|
)
|
||
|
|
|
||
|
|
// toSlogLevel converts a LoggerLevel into the corresponding slog.Level,
|
||
|
|
// defaulting to info for any unrecognized value.
|
||
|
|
func toSlogLevel(level LoggerLevel) slog.Level {
|
||
|
|
switch level {
|
||
|
|
case Development:
|
||
|
|
return slog.LevelDebug
|
||
|
|
case Production:
|
||
|
|
return slog.LevelInfo
|
||
|
|
default:
|
||
|
|
return slog.LevelInfo
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// New creates a *slog.Logger that writes to os.Stderr via slog's default
|
||
|
|
// TextHandler, with its verbosity driven by the given LoggerLevel. This
|
||
|
|
// replaces the legacy module-level singleton LOGGER; callers own the returned
|
||
|
|
// logger and thread it through to sub-modules.
|
||
|
|
func New(level LoggerLevel) *slog.Logger {
|
||
|
|
handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
|
||
|
|
Level: toSlogLevel(level),
|
||
|
|
})
|
||
|
|
return slog.New(handler)
|
||
|
|
}
|