1.项目介绍
Gin
框架学习使用,并实践常用包在Gin
框架中的集成和使用。源码地址: https://github.com/52lu/gin-import-template.git
1.1 项目结构
├── api ├── config ├── core ├── global ├── initialize ├── logs ├── main.go ├── model ├── router └── middleware ├── test └── utils
|
1.2 集成流程
2.安装
go get -u go.uber.org/zap
go get -u github.com/natefinch/lumberjack
|
3.配置
3.1 编辑app.yaml
... log: path: ./logs filePrefix: gin fileFormat: 2006-01-02 level: debug writeWay: file outFormat: json zap: outFormat: json lumberJack: maxSize: 1 maxBackups: 3 maxAge: 30 compress: false ...
|
3.2 新增对应结构体
新建文件:config/log.go
package config
type log struct { Path string `yaml:"path"` Level string `yaml:"level"` FilePrefix string `yaml:"filePrefix"` FileFormat string `yaml:"fileFormat"` OutFormat string `yaml:"outFormat"` LumberJack lumberJack `yaml:"lumberJack"` }
type lumberJack struct { MaxSize int `yaml:"maxSize"` MaxBackups int `yaml:"maxBackups"` MaxAge int `yaml:"maxAge"` Compress bool `yaml:"compress"` }
|
3.3 嵌入主配置
type ServerConfig struct { .... Log log `yaml:"log"` }
|
3.4 定义全局变量logger
编辑文件:global/global.go
var ( ... GvaLogger *zap.Logger )
|
4. 具体代码
4.1 集成入口(InitLogger
)
const ( outJson = "json" ) func InitLogger() { logConfig := global.GvaConfig.Log if exist, _ := utils.DirExist(logConfig.Path); !exist { _ = utils.CreateDir(logConfig.Path) } var encoder zapcore.Encoder if logConfig.OutFormat == outJson { encoder = zapcore.NewJSONEncoder(getEncoderConfig()) } else { encoder = zapcore.NewConsoleEncoder(getEncoderConfig()) } writeSyncer := zapcore.AddSync(getLumberjackWriteSyncer()) zapCore := zapcore.NewCore(encoder, writeSyncer, getLevel()) logger := zap.New(zapCore) defer logger.Sync() global.GvaLogger = logger }
|
4.2 获取最低记录级别
func getLevel() zapcore.Level { levelMap := map[string]zapcore.Level{ "debug": zapcore.DebugLevel, "info": zapcore.InfoLevel, "warn": zapcore.WarnLevel, "error": zapcore.ErrorLevel, "dpanic": zapcore.DPanicLevel, "panic": zapcore.PanicLevel, "fatal": zapcore.FatalLevel, } if level, ok := levelMap[global.GvaConfig.Log.Level]; ok { return level } return zapcore.InfoLevel }
|
4.3 自定义日志输出字段
func getEncoderConfig() zapcore.EncoderConfig { config := zapcore.EncoderConfig{ TimeKey: "time", LevelKey: "level", NameKey: "logger", CallerKey: "caller", FunctionKey: zapcore.OmitKey, MessageKey: "msg", StacktraceKey: "S", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.CapitalLevelEncoder, EncodeTime: getEncodeTime, EncodeDuration: zapcore.StringDurationEncoder, EncodeCaller: zapcore.ShortCallerEncoder, } return config }
func getEncodeTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) { enc.AppendString(t.Format("2006/01/02 - 15:04:05.000")) }
|
效果如下:
{"L":"INFO","T":"2021-07-06T11:59:10.763+0800","M":"Info记录","name":"张三"}
{"level":"INFO","time":"2021/07/06 - 11:59:29.906","msg":"Info记录","name":"张三"}
|
4.4 日志文件切割
func getLumberjackWriteSyncer() zapcore.WriteSyncer { lumberjackConfig := global.GvaConfig.Log.LumberJack lumberjackLogger := &lumberjack.Logger{ Filename: getLogFile(), MaxSize: lumberjackConfig.MaxSize, MaxBackups: lumberjackConfig.MaxBackups, MaxAge: lumberjackConfig.MaxAge, Compress: lumberjackConfig.Compress, } return zapcore.AddSync(lumberjackLogger) }
func getLogFile() string { fileFormat := time.Now().Format(global.GvaConfig.Log.FileFormat) fileName := strings.Join([]string{ global.GvaConfig.Log.FilePrefix, fileFormat, "log"}, ".") return path.Join(global.GvaConfig.Log.Path, fileName) }
|
5. 测试验证
global.GvaLogger.Sugar().Infof("日志写入测试: %v",strings.Repeat("hello",6))
global.GvaLogger.Info("Info记录",zap.String("name","张三"))
|