Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor InitGlobalLogger to Accept String Level Argument #14

Merged
merged 4 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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