package fslog import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "os" "path/filepath" "runtime/debug" "strings" "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()) }) } func Info(serviceName string, funcName string, callName string, message string) { lazyInitialize() callerFields := getCallerInfoForLog(serviceName, funcName, callName) logger.Info(message, callerFields...) } func Error(serviceName string, funcName string, callName string, message string) { lazyInitialize() callerFields := getCallerInfoForLog(serviceName, funcName, callName) logger.Error(message+"\n"+string(debug.Stack()), callerFields...) } func Debug(serviceName string, funcName string, callName string, message string) { lazyInitialize() callerFields := getCallerInfoForLog(serviceName, funcName, callName) logger.Debug(message, callerFields...) } func Warn(serviceName string, funcName string, callName string, message string) { lazyInitialize() callerFields := getCallerInfoForLog(serviceName, funcName, callName) logger.Warn(message, callerFields...) } func getCallerInfoForLog(serviceName string, funcName string, callName string) []zap.Field { fields := make([]zap.Field, 0) if strings.Trim(serviceName, " ") != "" { fields = append(fields, zap.String("service", serviceName)) } if strings.Trim(funcName, " ") != "" { fields = append(fields, zap.String("function", funcName)) } if strings.Trim(callName, " ") != "" { fields = append(fields, zap.String("call", callName)) } return fields } func pathExists(path string) bool { _, err := os.Stat(path) if err == nil { return true } if os.IsNotExist(err) { return false } return false }