乐趣区

关于golang:golang-zap日志库使用

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")
}
退出移动版