Skip to content

Commit

Permalink
add unit test for logger package
Browse files Browse the repository at this point in the history
  • Loading branch information
Yusuf Kanchwala committed Jul 26, 2020
1 parent fb4e51a commit de76066
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 3 deletions.
18 changes: 15 additions & 3 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,26 @@ func getLoggerLevel(lvl string) zapcore.Level {
// Init initializes global custom zap logger
func Init(encoding, level string) {

// select encoding level
encodingLevel := zapcore.LowercaseColorLevelEncoder
if encoding == "json" {
encodingLevel = zapcore.LowercaseLevelEncoder
}

// get logger
logger := GetLogger(level, encoding, encodingLevel)

// initialize global logger
zap.ReplaceGlobals(logger)
}

// GetLogger creates a customer zap logger
func GetLogger(logLevel, encoding string, encodingLevel func(zapcore.Level, zapcore.PrimitiveArrayEncoder)) *zap.Logger {

// build zap config
zapConfig := zap.Config{
Encoding: encoding,
Level: zap.NewAtomicLevelAt(getLoggerLevel(level)),
Level: zap.NewAtomicLevelAt(getLoggerLevel(logLevel)),
OutputPaths: []string{"stdout"},
EncoderConfig: zapcore.EncoderConfig{
LevelKey: "level",
Expand All @@ -48,8 +59,9 @@ func Init(encoding, level string) {
EncodeCaller: zapcore.ShortCallerEncoder,
},
}

// create zap logger
logger, _ := zapConfig.Build()

// initialize global logger
zap.ReplaceGlobals(logger)
return logger
}
73 changes: 73 additions & 0 deletions pkg/logger/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package logger

import (
"testing"

"go.uber.org/zap/zapcore"
)

func TestGetLoggerLevel(t *testing.T) {
table := []struct {
name string
input string
want zapcore.Level
}{
{
name: "empty log level",
input: "",
want: zapcore.InfoLevel,
},
{
name: "invalid log level",
input: "some log level",
want: zapcore.InfoLevel,
},
{
name: "debug log level",
input: "debug",
want: zapcore.DebugLevel,
},
{
name: "panic log level",
input: "panic",
want: zapcore.PanicLevel,
},
}

for _, tt := range table {
got := getLoggerLevel(tt.input)
if got != tt.want {
t.Errorf("got: '%v', want: '%v'", got, tt.want)
}
}
}

func TestGetLogger(t *testing.T) {

table := []struct {
name string
logLevel string
encoding string
encodingLevel func(zapcore.Level, zapcore.PrimitiveArrayEncoder)
}{
{
name: "check debug log level",
logLevel: "debug",
encoding: "json",
encodingLevel: zapcore.LowercaseLevelEncoder,
},
{
name: "check log level",
logLevel: "panic",
encoding: "console",
encodingLevel: zapcore.LowercaseLevelEncoder,
},
}

for _, tt := range table {
got := GetLogger(tt.logLevel, tt.encoding, tt.encodingLevel)
if ce := got.Check(getLoggerLevel(tt.logLevel), "testing"); ce == nil {
t.Errorf("unexpected error")
}
}
}

0 comments on commit de76066

Please sign in to comment.