|
| 1 | +package core |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "gin-vue-admin/global" |
| 6 | + "gin-vue-admin/utils" |
| 7 | + zaprotatelogs "github.com/lestrrat-go/file-rotatelogs" |
| 8 | + "go.uber.org/zap" |
| 9 | + "go.uber.org/zap/zapcore" |
| 10 | + "os" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + zapLogDir = "log" |
| 16 | + zapLogSoftLink = "latest_log" |
| 17 | + zapModule = "gin-vue-admin" |
| 18 | +) |
| 19 | + |
| 20 | +func init() { |
| 21 | + if global.GVA_CONFIG.Zap.File == "" { |
| 22 | + global.GVA_CONFIG.Zap.File = "DEBUG" |
| 23 | + } |
| 24 | + if ok, _ := utils.PathExists(zapLogDir); !ok { |
| 25 | + // directory not exist |
| 26 | + fmt.Println("create log directory") |
| 27 | + _ = os.Mkdir(zapLogDir, os.ModePerm) |
| 28 | + } |
| 29 | + var l = new(zapcore.Level) |
| 30 | + writeSyncer, err := getWriteSyncer() |
| 31 | + if err != nil { |
| 32 | + fmt.Printf("Get Write Syncer Failed err:%v", err.Error()) |
| 33 | + return |
| 34 | + } |
| 35 | + encoder := getEncoderConfig() |
| 36 | + if err := l.UnmarshalText([]byte(global.GVA_CONFIG.Zap.Level)); err != nil { |
| 37 | + fmt.Printf("Unmarshal Level Failed err:%v", err.Error()) |
| 38 | + return |
| 39 | + } |
| 40 | + core := zapcore.NewCore(encoder, writeSyncer, l) |
| 41 | + global.GVA_ZAP = zap.New(core, zap.AddCaller()) |
| 42 | +} |
| 43 | + |
| 44 | +// getWriteSyncer zap logger中加入file-rotatelogs |
| 45 | +func getWriteSyncer() (zapcore.WriteSyncer, error) { |
| 46 | + fileWriter, err := zaprotatelogs.New( |
| 47 | + zapLogDir + string(os.PathSeparator) + "%Y-%m-%d-%H-%M.log", |
| 48 | + zaprotatelogs.WithLinkName(zapLogSoftLink), |
| 49 | + zaprotatelogs.WithMaxAge(7*24*time.Hour), |
| 50 | + zaprotatelogs.WithRotationTime(24*time.Hour), |
| 51 | + ) |
| 52 | + return zapcore.AddSync(fileWriter), err |
| 53 | +} |
| 54 | + |
| 55 | +// getEncoderConfig 获取zapcore.Encoder |
| 56 | +func getEncoderConfig() zapcore.Encoder { |
| 57 | + encoderConfig := zap.NewProductionEncoderConfig() |
| 58 | + encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder |
| 59 | + encoderConfig.TimeKey = "time" |
| 60 | + encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder |
| 61 | + encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder |
| 62 | + encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder |
| 63 | + return zapcore.NewConsoleEncoder(encoderConfig) |
| 64 | +} |
| 65 | + |
| 66 | + |
| 67 | + |
0 commit comments