package fslog import ( "fmt" "go.uber.org/zap" "go.uber.org/zap/zapcore" "os" "path/filepath" "sync" ) const ( LoggerLevelInfo = "info" LoggerLevelError = "error" LoggerLevelDebug = "debug" LoggerLevelWarn = "Warn" ) var LoggerLever = LoggerLevelDebug func chooseLoggerLever() zapcore.Level { switch LoggerLever { case LoggerLevelInfo: return zapcore.InfoLevel case LoggerLevelError: return zapcore.ErrorLevel case LoggerLevelDebug: return zapcore.DebugLevel case LoggerLevelWarn: return zapcore.WarnLevel default: return zapcore.DebugLevel } } var logger *zap.Logger var initLoggerOnce sync.Once const logDir = "logs" func lazyInitialize() { initLoggerOnce.Do(func() { if !pathExists(logDir) { err := os.MkdirAll(logDir, os.ModeDir|os.ModePerm) if err != nil { panic(err) } } logFilePath := filepath.Join(logDir, "log") file, err := os.Create(logFilePath) if err != nil { panic(err) } developmentEncoderConfig := zap.NewDevelopmentEncoderConfig() encoder := zapcore.NewConsoleEncoder(developmentEncoderConfig) core := zapcore.NewTee( zapcore.NewCore(encoder, zapcore.AddSync(file), chooseLoggerLever()), zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), chooseLoggerLever()), ) logger = zap.New(core, zap.AddCaller(),zap.AddCallerSkip(1)) }) } func Info(message string) { lazyInitialize() logger.Info(message) } func Error(err error) { lazyInitialize() message:= fmt.Sprintf("\n%+v\n", err) logger.Error(message) } func Debug(message string) { lazyInitialize() logger.Debug(message) } func Warn(message string) { lazyInitialize() logger.Warn(message) } func pathExists(path string) bool { _, err := os.Stat(path) if err == nil { return true } if os.IsNotExist(err) { return false } return false }