all repos — website @ f0f14c101b7c37b8a4e7f90de1e53f8b3a2313b7

My website

log: enable setting log level from environment variable
Alan Pearce alan@alanpearce.eu
Wed, 19 Jun 2024 14:10:50 +0200
commit

f0f14c101b7c37b8a4e7f90de1e53f8b3a2313b7

parent

8002766378b1153e749297ed1d01ba221ee72b41

1 files changed, 14 insertions(+), 1 deletions(-)

jump to
M internal/log/log.gointernal/log/log.go
@@ -33,15 +33,28 @@ func Fatal(msg string, rest ...any) { 	logger.Fatalw(msg, rest...)
 }
 
+func getLevelFromEnv() (zapcore.Level, error) {
+	if str, found := os.LookupEnv("LOG_LEVEL"); found {
+		l, err := zap.ParseAtomicLevel(str)
+		return l.Level(), err
+	}
+	return zap.InfoLevel, nil
+}
+
 func Configure(isProduction bool) {
 	var l *zap.Logger
+	level, err := getLevelFromEnv()
+	if err != nil {
+		panic(err)
+	}
 	if isProduction {
 		cfg := zap.NewProductionEncoderConfig()
 		cfg.TimeKey = ""
-		l = zap.New(zapcore.NewCore(zaplogfmt.NewEncoder(cfg), os.Stderr, zapcore.InfoLevel))
+		l = zap.New(zapcore.NewCore(zaplogfmt.NewEncoder(cfg), os.Stderr, level))
 	} else {
 		cfg := prettyconsole.NewConfig()
 		cfg.EncoderConfig.TimeKey = ""
+		cfg.Level.SetLevel(level)
 		l = zap.Must(cfg.Build())
 	}
 	logger = l.WithOptions(zap.AddCallerSkip(1)).Sugar()