[TOC] >[github](https://github.com/uber-go/zap) ## 使用 ``` package main import ( "fmt" "os" "path" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" ) /** * 获取日志 * filePath 日志文件路径 * level 日志级别 只保存大于等于改级别的日志 * maxSize 每个日志文件保存的最大尺寸 单位:M * maxBackups 日志文件最多保存多少个备份 * maxAge 文件最多保存多少天 * compress 是否压缩 * serviceName 服务名 */ func NewLogger(filePath string, level zapcore.Level, maxSize int, maxBackups int, maxAge int, compress bool, serviceName string) *zap.Logger { dir := path.Dir(filePath) os.MkdirAll(dir, 0777) core := newCore(filePath, level, maxSize, maxBackups, maxAge, compress) //return zap.New(core, zap.AddCaller(), zap.Development(), zap.Fields(zap.String("serviceName", serviceName))) //可设置模块 return zap.New(core, zap.AddCaller()) } /** * zapcore构造 */ func newCore(filePath string, level zapcore.Level, maxSize int, maxBackups int, maxAge int, compress bool) zapcore.Core { //日志文件路径配置2 hook := lumberjack.Logger{ Filename: filePath, // 日志文件路径 MaxSize: maxSize, // 每个日志文件保存的最大尺寸 单位:M MaxBackups: maxBackups, // 日志文件最多保存多少个备份 MaxAge: maxAge, // 文件最多保存多少天 Compress: compress, // 是否压缩 } // 设置日志级别 atomicLevel := zap.NewAtomicLevel() atomicLevel.SetLevel(level) //公用编码器 encoderConfig := zapcore.EncoderConfig{ TimeKey: "time", LevelKey: "level", NameKey: "logger", CallerKey: "linenum", MessageKey: "msg", StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.LowercaseLevelEncoder, // 小写编码器 EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { enc.AppendString(t.Format("2006-01-02 15:04:05")) }, EncodeDuration: zapcore.SecondsDurationEncoder, // EncodeCaller: zapcore.ShortCallerEncoder, // 全路径编码器 EncodeName: zapcore.FullNameEncoder, } return zapcore.NewCore( zapcore.NewConsoleEncoder(encoderConfig), // 编码器配置 zapcore.NewJSONEncoder(encoderConfig) 与 zapcore.NewConsoleEncoder(encoderConfig) //zapcore.NewJSONEncoder(encoderConfig), // 编码器配置 zapcore.NewJSONEncoder(encoderConfig) 与 zapcore.NewConsoleEncoder(encoderConfig) zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(&hook)), // 打印到控制台和文件 atomicLevel, // 日志级别 ) } var MainLogger *zap.Logger var GatewayLogger *zap.Logger func init() { /** zapcore.DebugLevel 只保存大于 zapcore.DebugLevel 大于设置级别的日志 */ MainLogger = NewLogger("./logs/logs2/main.log", zapcore.DebugLevel, 10, 7, 7, true, "Main") GatewayLogger = NewLogger("./logs/logs2/gateway.log", zapcore.DebugLevel, 10, 7, 7, true, "Gateway") } func main() { for i := 0; i < 10; i++ { fmt.Println("init main") MainLogger.Debug("hello main Debug") MainLogger.Info("hello main Info") GatewayLogger.Debug("Hi Gateway Im Debug") GatewayLogger.Info("Hi Gateway Im Info") } } ```