1.zap安装

go get -u go.uber.org/zap

2.zap配置

Zap提供了两种类型的日志记录器,Sugared LoggerLogger

  • 在性能很好,但不关键的上下文中, 使用Suggered Logger, 比其他结构化日志记录快4-10倍, 并且支持结构化和print风格打印
  • 在每一次内存分配都很重要的上下文中,使用Logger.他甚至比Suggered Logger更快,分配内存次数也更少,但只支持强类型的结构化日志记录

1.zap.NewProduction() 生产环境

2.zap.NewDevelopment() 开发环境

3.zap.Example()

默认情况下,日志都会打印到console

3.zap使用demo

func (log *Logger) MethodXXX(msg string, fields ...Field) 
    logger.Error(
            "Error fetching url...",
            zap.String("url", url),
            zap.Error(err))

code:

var logger *zap.Logger
//var sugarLogger *zap.SugaredLogger

func InitLogger() {
    // 初始化
    logger, _ = zap.NewProduction()
    //sugarLogger = logger.Sugar()
}

func main() {
    InitLogger()
    defer logger.Sync()
    // 一次失败一次成功
    requestGoogle("www.google.com")
    requestGoogle("http://www.baidu.com")
}
func requestGoogle(url string) {
    resp, err := http.Get(url)
    if err != nil {
        //logger.Error(
        //  "Error fetching url...",
        //  zap.String("url", url),
        //  zap.Error(err))
        sugarLogger.Errorf("Error fetch url %s, Error:%s", url, err)
    } else {
        logger.Info(
            "url request success...",
            zap.String("url", url),
            zap.String("status code:", resp.Status))
        resp.Body.Close()
    }
}

{"level":"error","ts":1637481173.9171183,"msg":"Error fetch url http://www.google.com, Error:Get \"http://www.google.com\": dial tcp 31.13.67.20:80: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."}
{"level":"info","ts":1637481173.9862309,"msg":"url request success...","url":"http://www.baidu.com","status code:":"200 OK"}

Sugared Logger唯一的区别是:通过调用主logger的. Sugar()方法来获取一个SugaredLogger。然后使用SugaredLoggerprintf格式记录语句

code:

var logger *zap.Logger
var sugarLogger *zap.SugaredLogger

func InitLogger() {
    logger, _ = zap.NewProduction()
    sugarLogger = logger.Sugar()
}

func main() {
    InitLogger()
    defer logger.Sync()

    requestGoogle("www.google.com")
    requestGoogle("http://www.baidu.com")
}
func requestGoogle(url string) {
    resp, err := http.Get(url)
    if err != nil {
        sugarLogger.Errorf("Error fetch url %s, Error:%s", url, err)
    } else {
        logger.Info(
            "url request success...",
            zap.String("url", url),
            zap.String("status code:", resp.Status))
        resp.Body.Close()
    }
}

4.zap定制Logger 写入文件

使用zap.New(…)方法来手动传递所有配置,而不是使用像zap.NewProduction()这样的预置方法来创建logger。

func New(core zapcore.Core, options ...Option) *Logger

zapcore.Core需要三个配置——Encoder,WriteSyncer,LogLevel

  • Encoder:编码器(如何写入日志)。使用开箱即用的NewJSONEncoder(),并使用预先设置的ProductionEncoderConfig()。
  • WriterSyncer :指定日志将写到哪里去。使用zapcore.AddSync()函数并且将打开的文件句柄传进去。
  • Log Level:指定日志的级别
var logger *zap.Logger
func InitLogger() {
    writeSyncer := getLogWriter()
    encoder := getEncoder()
    core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

    logger = zap.New(core)
}

func getEncoder() zapcore.Encoder {
    return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
}

func getLogWriter() zapcore.WriteSyncer {
    // 一开始没有的时候create
    // file, _ := os.OpenFile("./test.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0744)
    file, _ := os.Create("./test.log")
    return zapcore.AddSync(file)
}
// 有test.log文件的时候
//file, _ := os.OpenFile("./test.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0744)

5.zap修改日期格式

func getEncoder() zapcore.Encoder {
    encoderConfig := zap.NewProductionEncoderConfig()
    encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
    encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
    return zapcore.NewConsoleEncoder(encoderConfig)
}

6.zap增加函数调用信息

在InitLogger里面

logger = zap.New(core, zap.AddCaller())
func initLogger() {
    writeSyncer := getLoggerWriter()
    encoder := getEncoder()
    core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

    logger = zap.New(core, zap.AddCaller()) // zap.addcaller:添加调用信息
    suggerlogger = logger.Sugar()
}

Lumberjack日志切割归档

安装:

go get -u github.com/natefinch/lumberjack
func getLoggerWriter() zapcore.WriteSyncer {
    //file, _ := os.OpenFile("./test.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0744)
    lumberJackLogger := &lumberjack.Logger{
        Filename:   "./test.log",
        MaxSize:    5, // 单位:M,进行切割之前,日志文件的最大大小
        MaxAge:     1, //最大备份天数
        MaxBackups: 2, // 最大备份数量
        LocalTime:  false,
        Compress:   true,
    }
    return zapcore.AddSync(lumberJackLogger)
}

完整代码:

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

var logger *zap.Logger
var suggerlogger *zap.SugaredLogger

func initLogger() {
    writeSyncer := getLoggerWriter()
    encoder := getEncoder()
    core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

    logger = zap.New(core, zap.AddCaller()) // zap.addcaller:添加调用信息
    suggerlogger = logger.Sugar()
}

func getEncoder() zapcore.Encoder {
    //return zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
    encoderConfig := zap.NewProductionEncoderConfig()
    encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
    encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
    return zapcore.NewConsoleEncoder(encoderConfig)
}
func getLoggerWriter() zapcore.WriteSyncer {
    //file, _ := os.OpenFile("./test.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0744)
    lumberJackLogger := &lumberjack.Logger{
        Filename:   "./test.log",
        MaxSize:    5, // 单位:M
        MaxAge:     1, //最大备份天数
        MaxBackups: 2, // 最大备份数量
        LocalTime:  false,
        Compress:   true,
    }
    return zapcore.AddSync(lumberJackLogger)
}

func main() {
    initLogger()

    for i := 0; i < 10000; i++ {
        logger.Info("test for lumberjack..")
    }

    requestGoogle2("http://www.sogo.com")
    requestGoogle2("http://www.baidu.com")
}
func requestGoogle2(url string) {
    resp, err := http.Get(url)
    if err != nil {
        logger.Error(
            "Error fetching url...",
            zap.String("url", url),
            zap.Error(err))
        //suggerlogger.Errorf("Error fetch url %s, Error:%s", url, err)
    } else {
        logger.Info(
            "url request success...",
            zap.String("url", url),
            zap.String("status code:", resp.Status))
        resp.Body.Close()
    }
}

站点统计

  • 文章总数:315 篇
  • 分类总数:20 个
  • 标签总数:193 个
  • 运行天数:1139 天
  • 访问总数:15254 人次

浙公网安备33011302000604

辽ICP备20003309号