From 4e5479c4f880d3c1c5ea09d061e897c5e71d0b0e Mon Sep 17 00:00:00 2001 From: Steffen Exler Date: Sat, 30 Apr 2022 17:04:27 +0200 Subject: [PATCH] feat(template): set zap loglevel via environment var (#92) * Set ZAP loglevel via environment var Signed-off-by: Steffen Exler * Update _template/cmd/{{.Base.appName}}/main.go Co-authored-by: Tobias Brumhard * Put logger logic into internal folder Signed-off-by: Steffen Exler * Rename logger.GetLogger to logger.NewAtLevel Signed-off-by: Tobias Brumhard Co-authored-by: Tobias Brumhard --- _template/cmd/{{.Base.appName}}/main.go | 3 ++- _template/internal/logger/logger.go | 27 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 _template/internal/logger/logger.go diff --git a/_template/cmd/{{.Base.appName}}/main.go b/_template/cmd/{{.Base.appName}}/main.go index f891779f..b5d000d6 100644 --- a/_template/cmd/{{.Base.appName}}/main.go +++ b/_template/cmd/{{.Base.appName}}/main.go @@ -4,6 +4,7 @@ import ( "fmt" "os" + "{{.Base.moduleName}}/internal/logger" "go.uber.org/zap" // This controls the maxprocs environment variable in container runtimes. @@ -19,7 +20,7 @@ func main() { } func run() error { - logger, err := zap.NewProduction() + logger, err := logger.NewAtLevel(os.Getenv("LOG_LEVEL")) if err != nil { return err } diff --git a/_template/internal/logger/logger.go b/_template/internal/logger/logger.go new file mode 100644 index 00000000..3f2597cb --- /dev/null +++ b/_template/internal/logger/logger.go @@ -0,0 +1,27 @@ +package logger + +import ( + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +func NewAtLevel(levelStr string) (*zap.Logger, error) { + logLevel := zapcore.InfoLevel + if levelStr != "" { + var err error + logLevel, err = zapcore.ParseLevel(levelStr) + if err != nil { + return nil, err + } + } + + logConf := zap.NewProductionConfig() + logConf.Level = zap.NewAtomicLevelAt(logLevel) + + logger, err := logConf.Build() + if err != nil { + return nil, err + } + + return logger, nil +}