2020-07-10 14:17:51 +00:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
2020-07-24 13:54:03 +00:00
|
|
|
"errors"
|
2020-07-10 14:17:51 +00:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"go.uber.org/zap/zapcore"
|
|
|
|
)
|
|
|
|
|
2020-07-24 13:54:03 +00:00
|
|
|
// Logger represents the component
|
|
|
|
// for writing messages to log.
|
|
|
|
//
|
|
|
|
// It is a type alias of
|
|
|
|
// go.uber.org/zap.Logger.
|
|
|
|
type Logger = zap.Logger
|
|
|
|
|
|
|
|
// ErrNilLogger is returned by functions that
|
|
|
|
// expect a non-nil Logger, but received nil.
|
|
|
|
var ErrNilLogger = errors.New("logger is nil")
|
2020-07-10 14:17:51 +00:00
|
|
|
|
|
|
|
// NewLogger is a logger's constructor.
|
2020-07-24 13:54:03 +00:00
|
|
|
func NewLogger(v *viper.Viper) (*Logger, error) {
|
2020-07-10 14:17:51 +00:00
|
|
|
c := zap.NewProductionConfig()
|
|
|
|
c.Level = safeLevel(v.GetString("logger.level"))
|
2021-05-11 08:17:45 +00:00
|
|
|
c.Encoding = "console"
|
2020-07-10 14:17:51 +00:00
|
|
|
c.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
|
|
|
|
2021-05-11 08:25:54 +00:00
|
|
|
return c.Build(
|
2021-05-11 08:17:45 +00:00
|
|
|
// record a stack trace for all messages at or above fatal level
|
|
|
|
zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel)),
|
|
|
|
)
|
2020-07-10 14:17:51 +00:00
|
|
|
}
|
2020-07-24 13:54:03 +00:00
|
|
|
|
|
|
|
func safeLevel(lvl string) zap.AtomicLevel {
|
|
|
|
switch strings.ToLower(lvl) {
|
|
|
|
case "debug":
|
|
|
|
return zap.NewAtomicLevelAt(zap.DebugLevel)
|
|
|
|
case "warn":
|
|
|
|
return zap.NewAtomicLevelAt(zap.WarnLevel)
|
|
|
|
case "error":
|
|
|
|
return zap.NewAtomicLevelAt(zap.ErrorLevel)
|
|
|
|
case "fatal":
|
|
|
|
return zap.NewAtomicLevelAt(zap.FatalLevel)
|
|
|
|
case "panic":
|
|
|
|
return zap.NewAtomicLevelAt(zap.PanicLevel)
|
|
|
|
default:
|
|
|
|
return zap.NewAtomicLevelAt(zap.InfoLevel)
|
|
|
|
}
|
|
|
|
}
|