123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
- package boots
- import (
- "fmt"
- "go-nc/configs/global"
- "go-nc/internal/utils"
- "os"
- "strconv"
- "strings"
- "time"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
- "gopkg.in/natefinch/lumberjack.v2"
- )
- var (
- level zapcore.Level // zap 日志等级
- options []zap.Option // zap 配置项
- )
- func InitLog() *zap.Logger {
- // 创建根目录
- createRootDir()
- // 设置日志等级
- setLogLevel()
- if global.App.Config.Log.ShowLine {
- options = append(options, zap.AddCaller())
- }
- // 初始化 zap
- return zap.New(getZapCore(), options...)
- }
- func createRootDir() {
- if ok, _ := utils.PathExists(global.App.Config.Log.RootDir); !ok {
- _ = os.Mkdir(global.App.Config.Log.RootDir, os.ModePerm)
- }
- }
- func setLogLevel() {
- switch global.App.Config.Log.Level {
- case "debug":
- level = zap.DebugLevel
- options = append(options, zap.AddStacktrace(level))
- case "info":
- level = zap.InfoLevel
- case "warn":
- level = zap.WarnLevel
- case "error":
- level = zap.ErrorLevel
- options = append(options, zap.AddStacktrace(level))
- case "dpanic":
- level = zap.DPanicLevel
- case "panic":
- level = zap.PanicLevel
- case "fatal":
- level = zap.FatalLevel
- default:
- level = zap.InfoLevel
- }
- }
- // 扩展 Zap
- func getZapCore() zapcore.Core {
- var encoder zapcore.Encoder
- // 调整编码器默认配置
- encoderConfig := zap.NewProductionEncoderConfig()
- encoderConfig.EncodeTime = func(time time.Time, encoder zapcore.PrimitiveArrayEncoder) {
- encoder.AppendString("\x1b[34m" + time.Format("["+"2006-01-02 15:04:05.000"+"]") + "\x1b[0m")
- }
- encoderConfig.EncodeLevel = func(l zapcore.Level, encoder zapcore.PrimitiveArrayEncoder) {
- // encoder.AppendString("\x1b[34m" + global.App.Config.App.Env + "." + l.String() + "\x1b[0m")
- encoder.AppendString("\x1b[34m ." + l.String() + "\x1b[0m")
- }
- encoderConfig.EncodeCaller = func(caller zapcore.EntryCaller, encoder zapcore.PrimitiveArrayEncoder) {
- // 通过判断空来防止调用时的空指针异常
- if caller.Defined {
- parts := strings.Split(caller.TrimmedPath(), "/")
- file := parts[len(parts)-1]
- encoder.AppendString("\x1b[32m" + file + ":" + strconv.Itoa(caller.Line) + "\x1b[0m")
- }
- }
- // 设置编码器
- if global.App.Config.Log.Format == "json" {
- encoder = zapcore.NewJSONEncoder(encoderConfig)
- } else {
- encoder = zapcore.NewConsoleEncoder(encoderConfig)
- }
- return zapcore.NewCore(encoder, getLogWriter(), level)
- }
- // 使用 lumberjack 作为日志写入器
- func getLogWriter() zapcore.WriteSyncer {
- file := &lumberjack.Logger{
- Filename: global.App.Config.Log.RootDir + "/" + global.App.Config.Log.Filename,
- MaxSize: global.App.Config.Log.MaxSize,
- MaxBackups: global.App.Config.Log.MaxBackups,
- MaxAge: global.App.Config.Log.MaxAge,
- Compress: global.App.Config.Log.Compress,
- }
- consoleWriter := zapcore.Lock(os.Stdout) // 使用控制台输出
- // 只输入到日志文件 zapcore.AddSync(file) 为日志文件
- // return zapcore.AddSync(file)
- // 同时输出到控制台和日志文件
- return zapcore.NewMultiWriteSyncer(zapcore.AddSync(file), consoleWriter)
- }
- // 初始化日志
- func InitLogger() *zap.Logger {
- // 配置 zap 日志
- encoderConfig := zapcore.EncoderConfig{
- MessageKey: "message",
- LevelKey: "level",
- TimeKey: "time",
- CallerKey: "caller",
- EncodeCaller: zapcore.ShortCallerEncoder,
- EncodeTime: customTimeEncoder,
- EncodeDuration: zapcore.SecondsDurationEncoder,
- EncodeLevel: zapcore.CapitalColorLevelEncoder,
- }
- config := zap.Config{
- Encoding: "console",
- Level: zap.NewAtomicLevelAt(zap.DebugLevel),
- OutputPaths: getOutputPaths(), // 将日志输出到 stdout 和 sql.log 文件
- ErrorOutputPaths: []string{"stderr"},
- EncoderConfig: encoderConfig,
- }
- logger, err := config.Build()
- if err != nil {
- fmt.Println("日志初始化失败:", err)
- return nil
- }
- defer func() {
- _ = logger.Sync()
- }()
- return logger
- }
- // customTimeEncoder 自定义时间编码器
- func customTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
- enc.AppendString(fmt.Sprintf("\x1b[34m[%s]\x1b[0m", t.Format("2006-01-02 15:04:05.000")))
- }
- // getOutputPaths 获取日志输出路径
- func getOutputPaths() []string {
- if global.App.Config.Database.Mysql.EnableFileLogWriter {
- return []string{"stdout", global.App.Config.Database.Mysql.LogFilename}
- }
- return []string{"stdout"}
- }
|