picgo/corelib/log.go

54 lines
1.3 KiB
Go
Raw Normal View History

2024-07-12 20:32:33 +08:00
package corelib
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
"log"
"os"
"path"
"picgo/configs"
)
var Logger *zap.SugaredLogger
func NewLogger() {
writeSyncer := getLogWriter()
encoder := getEncoder()
core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
logger := zap.New(core, zap.AddCaller())
Logger = logger.Sugar()
}
func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
return zapcore.NewConsoleEncoder(encoderConfig)
}
func getLogWriter() zapcore.WriteSyncer {
var (
err error
currentDir string
)
// 获取当前工作目录
if currentDir, err = os.Getwd(); err != nil {
log.Panic("获取当前工作目录失败: ", err)
}
logPath := path.Join(currentDir, configs.Settings.Server.LogPath)
// Filename: 日志文件的位置
// MaxSize在进行切割之前日志文件的最大大小以 MB 为单位)
// MaxBackups保留旧文件的最大个数
// MaxAges保留旧文件的最大天数
// Compress是否压缩 / 归档旧文件
lumberJackLogger := &lumberjack.Logger{
Filename: logPath,
MaxSize: 50,
MaxBackups: 10,
MaxAge: 1,
Compress: false,
}
return zapcore.AddSync(lumberJackLogger)
}