1.安装zap

go get go.uber.org/zap

go get github.com/natefinch/lumberjack  //日志文件分割包

2.基本使用

func main() {
    logger, _ := zap.NewProduction() //生产环境实例
    defer logger.Sync()   //将缓存中的日志同步到文件中

    url := "http://xiayuedu.com"
    logger.Info("info",                 //info级别的日志
        zap.String("url",url),
        zap.Bool("bool",true),
    )
    logger.Info("info",
        zap.Namespace("namespace-1"),   //定义多级日志
        zap.String("url",url),          //使用对应的类型
        zap.Bool("bool",true),
    )
    logger.Info("info",
        zap.Namespace("namespace-2"),
        zap.String("url",url),
        zap.Bool("bool",true),
        )
    logger.Error("password is error",       //error级别
        zap.String("username","zhangsan"), 
        zap.String("password","123456"),  
    )
    logger.Debug("record user info",      //debug级别
        zap.String("username","zhangsan"),
        zap.String("password","123456"),
    )

    sugar := logger.Sugar()             //使用非zap.xxxx类型进行输出,性能较低,非核心代码处可以使用
    sugar.Info("sugar info",true,"123q342534",time.Second)
    sugar.Error("sugar info",true,"123q342534",time.Second)
    sugar.Debug("sugar info",true,"123q342534",time.Second)
    sugar.Warn("sugar info",true,"123q342534",time.Second)

}

输出结果

{"level":"info","ts":1627910714.8048513,"caller":"golangdemo/main.go:357","msg":"info","url":"http://xiayuedu.com","bool":true}
{"level":"info","ts":1627910714.805827,"caller":"golangdemo/main.go:361","msg":"info","namespace-1":{"url":"http://xiayuedu.com","bool":true}}
{"level":"info","ts":1627910714.806803,"caller":"golangdemo/main.go:366","msg":"info","namespace-2":{"url":"http://xiayuedu.com","bool":true}}
{"level":"error","ts":1627910714.806803,"caller":"golangdemo/main.go:371","msg":"password is error","username":"zhangsan","password":"123456","stacktrace":"main.ma
in\n\tC:/Users/admin/xiayuedu/golangdemo/main.go:371\nruntime.main\n\tC:/Program Files/Go/src/runtime/proc.go:203"}
{"level":"info","ts":1627910714.8077793,"caller":"golangdemo/main.go:381","msg":"sugar infotrue123q3425341s"}
{"level":"error","ts":1627910714.8077793,"caller":"golangdemo/main.go:382","msg":"sugar infotrue123q3425341s","stacktrace":"main.main\n\tC:/Users/admin/xiayuedu/go
langdemo/main.go:382\nruntime.main\n\tC:/Program Files/Go/src/runtime/proc.go:203"}
{"level":"warn","ts":1627910714.8087556,"caller":"golangdemo/main.go:384","msg":"sugar infotrue123q3425341s"}

3.定制化使用

拷贝来自https://www.jianshu.com/p/910...,大佬写的很不错很详细,可以满足生产使用


import (
    "fmt"
    "github.com/natefinch/lumberjack"
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    "os"
    "net/http"
)

var log *zap.Logger

func main() {
    var coreArr []zapcore.Core

    //获取编码器
    encoderConfig := zap.NewProductionEncoderConfig()               //NewJSONEncoder()输出json格式,NewConsoleEncoder()输出普通文本格式
    encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder           //指定时间格式
    encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder    //按级别显示不同颜色,不需要的话取值zapcore.CapitalLevelEncoder就可以了
    //encoderConfig.EncodeCaller = zapcore.FullCallerEncoder        //显示完整文件路径
    encoder := zapcore.NewConsoleEncoder(encoderConfig)

    //日志级别
    highPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool{  //error级别
        return lev >= zap.ErrorLevel
    })
    lowPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {  //info和debug级别,debug级别是最低的
        return lev < zap.ErrorLevel && lev >= zap.DebugLevel
    })

    //info文件writeSyncer
    infoFileWriteSyncer := zapcore.AddSync(&lumberjack.Logger{
        Filename:   "./log/info.log",   //日志文件存放目录,如果文件夹不存在会自动创建
        MaxSize:    2,                  //文件大小限制,单位MB
        MaxBackups: 100,                //最大保留日志文件数量
        MaxAge:     30,                 //日志文件保留天数
        Compress:   false,              //是否压缩处理
    })
    infoFileCore := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(infoFileWriteSyncer,zapcore.AddSync(os.Stdout)), lowPriority) //第三个及之后的参数为写入文件的日志级别,ErrorLevel模式只记录error级别的日志
    //error文件writeSyncer
    errorFileWriteSyncer := zapcore.AddSync(&lumberjack.Logger{
        Filename:   "./log/error.log",      //日志文件存放目录
        MaxSize:    1,                      //文件大小限制,单位MB
        MaxBackups: 5,                      //最大保留日志文件数量
        MaxAge:     30,                     //日志文件保留天数
        Compress:   false,                  //是否压缩处理
    })
    errorFileCore := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(errorFileWriteSyncer,zapcore.AddSync(os.Stdout)), highPriority) //第三个及之后的参数为写入文件的日志级别,ErrorLevel模式只记录error级别的日志

    coreArr = append(coreArr, infoFileCore)
    coreArr = append(coreArr, errorFileCore)
    log = zap.New(zapcore.NewTee(coreArr...), zap.AddCaller()) //zap.AddCaller()为显示文件名和行号,可省略


    log.Info("hello info")
    log.Debug("hello debug")
    log.Error("hello error")
}

你若安好便是晴天
82 声望10 粉丝