Skip to content

Commit

Permalink
Refactor InitGlobalLogger to Accept String Level Argument
Browse files Browse the repository at this point in the history
* Add level to logger

* Minor fix on InigGlobalLogger

* Add error to InitGlobalLogger

* Fix linter
  • Loading branch information
lucaslopezf authored Sep 14, 2023
1 parent 6420004 commit 7ba291b
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 6 deletions.
2 changes: 1 addition & 1 deletion cmd/demo-metrics/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
func main() {
println("[Demo] Microservice example")

cli.InitGlobalLogger()
_, _ = cli.InitGlobalLogger(cli.DebugLevel)

r := runner.NewRunner()

Expand Down
2 changes: 1 addition & 1 deletion cmd/demo-panic/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
func main() {
println("[Demo] Panic handler")

cli.InitGlobalLogger()
_, _ = cli.InitGlobalLogger(cli.DebugLevel)

r := runner.NewRunner()

Expand Down
31 changes: 28 additions & 3 deletions pkg/cli/logging.go
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 1 addition & 1 deletion pkg/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit 7ba291b

Please sign in to comment.