diff --git a/cmd/demo-metrics/main.go b/cmd/demo-metrics/main.go index 1af2c0f..94a5f30 100644 --- a/cmd/demo-metrics/main.go +++ b/cmd/demo-metrics/main.go @@ -9,7 +9,7 @@ import ( func main() { println("[Demo] Microservice example") - cli.InitGlobalLogger() + _, _ = cli.InitGlobalLogger(cli.DebugLevel) r := runner.NewRunner() diff --git a/cmd/demo-panic/main.go b/cmd/demo-panic/main.go index 0b031dc..5f0a594 100644 --- a/cmd/demo-panic/main.go +++ b/cmd/demo-panic/main.go @@ -9,7 +9,7 @@ import ( func main() { println("[Demo] Panic handler") - cli.InitGlobalLogger() + _, _ = cli.InitGlobalLogger(cli.DebugLevel) r := runner.NewRunner() diff --git a/pkg/cli/logging.go b/pkg/cli/logging.go index 29b3429..766d0fe 100644 --- a/pkg/cli/logging.go +++ b/pkg/cli/logging.go @@ -1,21 +1,46 @@ package cli import ( + "errors" "go.uber.org/zap" "go.uber.org/zap/zapcore" "os" + "strings" ) -func InitGlobalLogger() *zap.Logger { +const ( + DebugLevel = "debug" + InfoLevel = "info" + WarnLevel = "warn" + ErrorLevel = "error" + FatalLevel = "fatal" + PanicLevel = "panic" +) + +var stringToLevel = map[string]zapcore.Level{ + DebugLevel: zapcore.DebugLevel, + InfoLevel: zapcore.InfoLevel, + WarnLevel: zapcore.WarnLevel, + ErrorLevel: zapcore.ErrorLevel, + FatalLevel: zapcore.FatalLevel, + PanicLevel: zapcore.PanicLevel, +} + +func InitGlobalLogger(level string) (*zap.Logger, error) { + zapLevel, ok := stringToLevel[strings.ToLower(level)] + if !ok { + return nil, errors.New("log level '%s' is incorrect") + } + encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder encoder := zapcore.NewConsoleEncoder(encoderConfig) - core := zapcore.NewCore(encoder, os.Stdout, zapcore.DebugLevel) + core := zapcore.NewCore(encoder, os.Stdout, zapLevel) logger := zap.New(core) zap.ReplaceGlobals(logger) - return logger + return logger, nil } diff --git a/pkg/cli/root.go b/pkg/cli/root.go index 45a4152..6ecf829 100644 --- a/pkg/cli/root.go +++ b/pkg/cli/root.go @@ -69,7 +69,7 @@ func (c *CLI) init() { // TODO: We can make this optional? and more configurable if we see the need // Initialize logger - InitGlobalLogger() + _, _ = InitGlobalLogger(DebugLevel) setupCloseHandler(nil) // Set Configuration Defaults setupDefaultConfiguration(func() {