From b4346600c3c6454ec5b965bac07cec159a61a782 Mon Sep 17 00:00:00 2001 From: SliverHorn <503551462@qq.com> Date: Thu, 3 Sep 2020 16:25:52 +0800 Subject: [PATCH] =?UTF-8?q?zap=E6=97=A5=E5=BF=97=E7=9A=84=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E4=BC=98=E5=8C=96=E5=8F=8A=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/config.yaml | 14 ++++--- server/config/config.go | 12 +++--- server/core/zap.go | 93 ++++++++++++++++++++++++++++------------- 3 files changed, 81 insertions(+), 38 deletions(-) diff --git a/server/config.yaml b/server/config.yaml index c0037af9..b39b1d07 100644 --- a/server/config.yaml +++ b/server/config.yaml @@ -68,8 +68,12 @@ log: # zap logger configuration zap: - level: "debug" - file: "DEBUG" - max_size: 200 - max_age: 30 - max_backups: 7 \ No newline at end of file + # 可使用 "debug", "info", "warn", "error", "dpanic", "panic", "fatal", + level: 'debug' + # console: 控制台, json: json格式输出 + format: 'console' + prefix: '[GIN-VUE-ADMIN]' + director: 'logs' + link_name: 'ZapLatestLog' + show_line: true + log_in_console: true \ No newline at end of file diff --git a/server/config/config.go b/server/config/config.go index 40afe12d..147bfabd 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -81,9 +81,11 @@ type Sqlite struct { } type Zap struct { - Level string `json:"level"` - File string `json:"file"` - MaxSize int `json:"maxsize"` - MaxAge int `json:"max_age"` - MaxBackups int `json:"max_backups"` + Level string `mapstructure:"level" json:"level" yaml:"level"` + Format string `mapstructure:"format" json:"format" yaml:"format"` + Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` + Director string `mapstructure:"director" json:"director" yaml:"director"` + LinkName string `mapstructure:"link_name" json:"linkName" yaml:"link_name"` + ShowLine bool `mapstructure:"show_line" json:"show_line" yaml:"show_line"` + LogInConsole bool `mapstructure:"log_in_console" json:"logInConsole" yaml:"log_in_console"` } diff --git a/server/core/zap.go b/server/core/zap.go index 984edb52..128ef9f2 100644 --- a/server/core/zap.go +++ b/server/core/zap.go @@ -11,57 +11,94 @@ import ( "time" ) -const ( - zapLogDir = "log" - zapLogSoftLink = "latest_log" - zapModule = "gin-vue-admin" +var ( + err error + level zapcore.Level + writer zapcore.WriteSyncer ) func init() { - if global.GVA_CONFIG.Zap.File == "" { - global.GVA_CONFIG.Zap.File = "DEBUG" + if ok, _ := utils.PathExists(global.GVA_CONFIG.Zap.Director); !ok { // 判断是否有logs文件夹 + fmt.Println("create logs directory") // directory not exist + _ = os.Mkdir(global.GVA_CONFIG.Zap.Director, os.ModePerm) } - if ok, _ := utils.PathExists(zapLogDir); !ok { - // directory not exist - fmt.Println("create log directory") - _ = os.Mkdir(zapLogDir, os.ModePerm) + + switch global.GVA_CONFIG.Zap.Level {// 初始化配置文件的Level + case "debug": + level = zap.DebugLevel + case "info": + level = zap.InfoLevel + case "warn": + level = zap.WarnLevel + case "error": + level = zap.ErrorLevel + default: + level = zap.InfoLevel } - var l = new(zapcore.Level) - writeSyncer, err := getWriteSyncer() + + writer, err = getWriteSyncer() // 使用file-rotatelogs进行日志分割 if err != nil { fmt.Printf("Get Write Syncer Failed err:%v", err.Error()) return } - encoder := getEncoderConfig() - if err := l.UnmarshalText([]byte(global.GVA_CONFIG.Zap.Level)); err != nil { - fmt.Printf("Unmarshal Level Failed err:%v", err.Error()) + + if level == zap.DebugLevel || level == zap.ErrorLevel { + global.GVA_ZAP = zap.New(getEncoderCore(), zap.AddStacktrace(level)) + if global.GVA_CONFIG.Zap.ShowLine { + global.GVA_ZAP.WithOptions(zap.AddCaller()) + } return } - core := zapcore.NewCore(encoder, writeSyncer, l) - global.GVA_ZAP = zap.New(core, zap.AddCaller()) + global.GVA_ZAP = zap.New(getEncoderCore()) + if global.GVA_CONFIG.Zap.ShowLine { + global.GVA_ZAP.WithOptions(zap.AddCaller()) + } + } // getWriteSyncer zap logger中加入file-rotatelogs func getWriteSyncer() (zapcore.WriteSyncer, error) { fileWriter, err := zaprotatelogs.New( - zapLogDir + string(os.PathSeparator) + "%Y-%m-%d-%H-%M.log", - zaprotatelogs.WithLinkName(zapLogSoftLink), + global.GVA_CONFIG.Zap.Director+string(os.PathSeparator)+"%Y-%m-%d-%H-%M.log", + zaprotatelogs.WithLinkName(global.GVA_CONFIG.Zap.LinkName), zaprotatelogs.WithMaxAge(7*24*time.Hour), zaprotatelogs.WithRotationTime(24*time.Hour), ) + if global.GVA_CONFIG.Zap.LogInConsole { + return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter)), err + } return zapcore.AddSync(fileWriter), err } -// getEncoderConfig 获取zapcore.Encoder -func getEncoderConfig() zapcore.Encoder { - encoderConfig := zap.NewProductionEncoderConfig() - encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder - encoderConfig.TimeKey = "time" - encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder - encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder - encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder - return zapcore.NewConsoleEncoder(encoderConfig) +// getEncoderConfig 获取zapcore.EncoderConfig +func getEncoderConfig() (config zapcore.EncoderConfig) { + config = zapcore.EncoderConfig{ + MessageKey: "message", + LevelKey: "level", + TimeKey: "time", + NameKey: "logger", + CallerKey: "caller", + StacktraceKey: "stacktrace", + LineEnding: zapcore.DefaultLineEnding, + EncodeLevel: zapcore.CapitalColorLevelEncoder, + EncodeTime: CustomTimeEncoder, + EncodeDuration: zapcore.SecondsDurationEncoder, + EncodeCaller: zapcore.FullCallerEncoder, + } + return config } +// getEncoder 获取zapcore.Encoder +func getEncoder() zapcore.Encoder { + return zapcore.NewConsoleEncoder(getEncoderConfig()) +} +// getEncoderCore 获取Encoder的zapcore.Core +func getEncoderCore() (core zapcore.Core) { + return zapcore.NewCore(getEncoder(), writer, level) +} +// 自定义日志输出时间格式 +func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { + enc.AppendString(t.Format(global.GVA_CONFIG.Zap.Prefix+"2006/01/02 - 15:04:05.000")) +}