github.com/lovung/GoCleanArchitecture@v0.0.0-20210302152432-50d91fd29f9f/pkg/logger/logger.go (about) 1 package logger 2 3 import ( 4 "fmt" 5 "sync" 6 7 "go.uber.org/zap" 8 ) 9 10 // LogLevel definition 11 type LogLevel string 12 13 // LogLevel constants 14 const ( 15 DebugLevel LogLevel = "debug" 16 InfoLevel LogLevel = "info" 17 WarnLevel LogLevel = "warn" 18 ErrorLevel LogLevel = "error" 19 ) 20 21 var ( 22 once sync.Once 23 singleton *zap.Logger 24 ) 25 26 // Init the instance of logger 27 func Init(debug bool) { 28 once.Do(func() { 29 var err error 30 if debug { 31 singleton, err = zap.NewDevelopment() 32 } else { 33 singleton, err = zap.NewProduction() 34 } 35 if err != nil { 36 panic(err) 37 } 38 }) 39 } 40 41 // Instance the logger instance 42 func Instance() *zap.Logger { 43 return singleton 44 } 45 46 // SetLevel to set the new level for logger 47 func SetLevel(logLevel string) { 48 switch LogLevel(logLevel) { 49 case DebugLevel: 50 singleton.Core().Enabled(zap.DebugLevel) 51 case InfoLevel: 52 singleton.Core().Enabled(zap.InfoLevel) 53 case WarnLevel: 54 singleton.Core().Enabled(zap.WarnLevel) 55 case ErrorLevel: 56 singleton.Core().Enabled(zap.ErrorLevel) 57 default: 58 singleton.Core().Enabled(zap.InfoLevel) 59 } 60 } 61 62 // Printf is converted to an Info call because Zap does not have Printf() 63 func Printf(s string, i ...interface{}) { 64 singleton.Info(fmt.Sprintf(s, i...)) 65 } 66 67 // Debug logs as the debug level 68 func Debug(i ...interface{}) { 69 singleton.Debug(fmt.Sprint(i...)) 70 } 71 72 // Debugf logs as the debug level 73 func Debugf(s string, i ...interface{}) { 74 singleton.Debug(fmt.Sprintf(s, i...)) 75 } 76 77 // Info logs as the info level 78 func Info(i ...interface{}) { 79 singleton.Info(fmt.Sprint(i...)) 80 } 81 82 // Infof logs as the info level 83 func Infof(s string, i ...interface{}) { 84 singleton.Info(fmt.Sprintf(s, i...)) 85 } 86 87 // Warn logs as the WARN level 88 func Warn(i ...interface{}) { 89 singleton.Warn(fmt.Sprint(i...)) 90 } 91 92 // Warnf logs as the WARN level 93 func Warnf(s string, i ...interface{}) { 94 singleton.Warn(fmt.Sprintf(s, i...)) 95 } 96 97 // Error logs as the ERROR level 98 func Error(i ...interface{}) { 99 singleton.Error(fmt.Sprint(i...)) 100 } 101 102 // Errorf logs as the ERROR level 103 func Errorf(s string, i ...interface{}) { 104 singleton.Error(fmt.Sprintf(s, i...)) 105 }