go语言中开箱即用日志包:zap日志简单使用示例

2023-06-01 00:00:00 示例 日志 开箱

zap包介绍:Go中快速、结构化、分级的日志记录

安装zap包

go get -u go.uber.org/zap

请注意,zap仅支持Go的两个最新次要版本。


git:

https://github.com/uber-go/zap

官方手册:

https://pkg.go.dev/go.uber.org/zap#section-readme

zap支持的数据类型:

https://pkg.go.dev/go.uber.org/zap#Field

zap日志打印方法等级:

https://pkg.go.dev/go.uber.org/zap#Logger


代码示例:


初始化

package logZap

var Logger *zap.Logger

func Init() {
    var path string
    var serverName ="app_name"
    path = "/var/log/"
   
    if runtime.GOOS == "windows" {
        path = "./"
    } else {
        path = "/var/log/" + serverName + "/"
    }
   
    pathInfo := path + core.New().ServerInfo.ServerName + "_info.log"
    pathError := path + core.New().ServerInfo.ServerName + "_error.log"
    var err error
    Logger, err = GetLogger(pathInfo, pathError)
   
    if err != nil {
        panic(err)
    }
}

func GetLogger(infoPath, errorPath string) (*zap.Logger, error) {

    highPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
        return lev >= zap.ErrorLevel
    })
   
    lowPriority := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
        return lev < zap.ErrorLevel && lev >= zap.DebugLevel
    })
   
    prodEncoder := zap.NewProductionEncoderConfig()
    prodEncoder.EncodeTime = zapcore.ISO8601TimeEncoder
   
    lowWriteSyncer, lowClose, err := zap.Open(infoPath)
    if err != nil {
        lowClose()
        return nil, err
    }
   
    highWriteSyncer, highClose, err := zap.Open(errorPath)
    if err != nil {
        highClose()
        return nil, err
    }
   
    highCore := zapcore.NewCore(zapcore.NewJSONEncoder(prodEncoder), highWriteSyncer, highPriority)
    lowCore := zapcore.NewCore(zapcore.NewJSONEncoder(prodEncoder), lowWriteSyncer, lowPriority)
   
    return zap.New(zapcore.NewTee(highCore, lowCore), zap.AddCaller()), nil
}


使用调用

打印错误:

logZap.Logger.Error("error:", zap.Error(err))

打印debug:

logZap.Logger.Debug("port form:",zap.String("portStr",portStr))

相关文章