使用Lumberjack进行日志切割归档



上述程序中唯一缺少的就是日志切割归档功能。

但是Zap库本身不支持切割归档日志文件。

为了添加日志切割归档功能,我们将使用第三方库Lumberjack来实现。

安装

执行下面的命令安装Lumberjack

go get github.com/natefinch/lumberjack

zap logger中加入Lumberjack

要在zap中加入Lumberjack支持,我们需要修改WriteSyncer代码。我们将按照下面的代码修改getLogWriter()函数:

func getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./test.log",
		MaxSize:    10,
		MaxBackups: 5,
		MaxAge:     30,
		Compress:   false,
	}
	return zapcore.AddSync(lumberJackLogger)
}

Lumberjack Logger采用以下属性作为输入:

  • Filename: 日志文件的位置
  • MaxSize:在进行切割之前,日志文件的最大大小(以MB为单位)
  • MaxBackups:保留旧文件的最大个数
  • MaxAges:保留旧文件的最大天数
  • Compress:是否压缩/归档旧文件

测试所有功能

最终,使用Zap/Lumberjack logger的完整示例代码如下:

package main

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

var sugarLogger *zap.SugaredLogger

func main() {
	InitLogger()
	defer sugarLogger.Sync()
	simpleHttpGet("www.google.com")
	simpleHttpGet("http://www.google.com")
}

func InitLogger() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

	logger := zap.New(core, zap.AddCaller())
	sugarLogger = logger.Sugar()
}

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

func getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./test.log",
		MaxSize:    10,
		MaxBackups: 5,
		MaxAge:     30,
		Compress:   false,
	}
	return zapcore.AddSync(lumberJackLogger)
}


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中:

2022-03-24T23:38:57+08:00	DEBUG	SugaredLogger/main.go:42	Trying to hit GET request for www.google.com
2022-03-24T23:38:57+08:00	ERROR	SugaredLogger/main.go:45	Error fetching URL www.google.com : Error = Get "www.google.com": unsupported protocol scheme ""
2022-03-24T23:38:57+08:00	DEBUG	SugaredLogger/main.go:42	Trying to hit GET request for http://www.google.com
2022-03-24T23:39:18+08:00	ERROR	SugaredLogger/main.go:45	Error fetching URL http://www.google.com : Error = Get "http://www.google.com": dial tcp 108.160.162.102: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.
2022-03-24T23:48:14+08:00	DEBUG	10Lumberjack/main.go:48	Trying to hit GET request for www.google.com
2022-03-24T23:48:14+08:00	ERROR	10Lumberjack/main.go:51	Error fetching URL www.google.com : Error = Get "www.google.com": unsupported protocol scheme ""
2022-03-24T23:48:14+08:00	DEBUG	10Lumberjack/main.go:48	Trying to hit GET request for http://www.google.com
2022-03-24T23:48:35+08:00	ERROR	10Lumberjack/main.go:51	Error fetching URL http://www.google.com : Error = Get "http://www.google.com": dial tcp 173.252.108.21: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.

同时,可以在main函数中循环记录日志,测试日志文件是否会自动切割和归档(日志文件每1MB会切割并且在当前目录下最多保存5个备份)。

承接上文:

使用Uber-go Zap日志库


参考资料:

https://www.liwenzhou.com/posts/Go/zap/

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐