go实现zap logger

Zap logger

2021年5月7日
23:17

定制的Sugared Logger
学习网址:https://www.liwenzhou.com/posts/Go/zap/
代码:

package main
import (
    "net/http"
    "os"
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
)
var sugarLogger *zap.SugaredLogger
func main() {
    InitLogger()
    defer sugarLogger.Sync() // 将 buffer缓存 中的日志写到文件中
    simpleHttpGet("www.baidu.com")
    simpleHttpGet("http://www.baidu.com")
}
//初始化一个logger
func InitLogger() {
    // logger, _ := zap.NewProduction() //zap.NewProduction()/zap.NewDevelopment()或者zap.Example(),区别在于它将记录的信息不同
    // sugarLogger = logger.Sugar()
    writeSyncer := getLogWriter()
    encoder := getEncoder()
    core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
    //添加将调用函数信息记录到日志中的功能
    logger := zap.New(core, zap.AddCaller())
    sugarLogger = logger.Sugar()
}
func getEncoder() zapcore.Encoder {
    //覆盖默认的ProductionConfig()
    //修改时间编码器
    //在日志文件中使用大写字母记录日志级别
    encoderConfig := zap.NewProductionEncoderConfig()
    encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
    encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
    return zapcore.NewConsoleEncoder(encoderConfig)
}
//创建保存日志的文件
func getLogWriter() zapcore.WriteSyncer {
    file, _ := os.Create("./test.log")
    return zapcore.AddSync(file)
}
func simpleHttpGet(url string) {
    sugarLogger.Debugf("Trying to hit GET request for %s", url)
    resp, err := http.Get(url)
    if err != nil {
        sugarLogger.Errorf("Error fetching URL %s : Error = %s", url, err)
    } else {
        sugarLogger.Infof("Success! statusCode = %s for URL %s", resp.Status, url)
        resp.Body.Close()
    }
}

  

 

创建同级的test.log文件并记录日志信息如下:

2021-05-07T23:15:15.992+0800    DEBUG   GoZap/main.go:49    Trying to hit GET request for www.baidu.com
2021-05-07T23:15:16.009+0800    ERROR   GoZap/main.go:52    Error fetching URL www.baidu.com : Error = Get "www.baidu.com": unsupported protocol scheme ""
2021-05-07T23:15:16.009+0800    DEBUG   GoZap/main.go:49    Trying to hit GET request for http://www.baidu.com
2021-05-07T23:15:16.068+0800    INFO    GoZap/main.go:54    Success! statusCode = 200 OK for URL http://www.baidu.com

  

 

posted @ 2021-05-07 23:32  秋月桐  阅读(540)  评论(0编辑  收藏  举报