go:用zap和go-file-rotatelogs实现日志的记录和日志按时间分割
一,安装zap和go-file-rotatelogs两个库:
1,安装zap:
liuhongdi@ku:/data/liuhongdi/zaplog$ go get -u go.uber.org/zap
2,安装go-file-rotatelogs
liuhongdi@ku:/data/liuhongdi/zaplog2$ go get -u github.com/lestrrat/go-file-rotatelogs
3, go-file-rotatelogs的源码地址:
https://github.com/lestrrat/go-file-rotatelogs
说明:刘宏缔的go森林是一个专注golang的博客,
地址:https://blog.csdn.net/weixin_43881017
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,演示项目的相关信息
1,项目地址:
https://github.com/liuhongdi/zaplog2
三,代码说明
main.go
-
package main
-
-
import (
-
"fmt"
-
rotatelogs "github.com/lestrrat/go-file-rotatelogs"
-
"go.uber.org/zap"
-
"go.uber.org/zap/zapcore"
-
"io"
-
"net/http"
-
"time"
-
)
-
-
var sugarLogger *zap.SugaredLogger
-
-
func main() {
-
fmt.Println("begin main")
-
InitLogger()
-
defer sugarLogger.Sync()
-
simpleHttpGet("www.cnblogs.com")
-
simpleHttpGet("https://www.baidu.com")
-
}
-
-
//例子,http访问url,返回状态
-
func simpleHttpGet(url string) {
-
fmt.Println("begin simpleHttpGet:"+url)
-
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()
-
}
-
}
-
-
func InitLogger() {
-
encoder := getEncoder()
-
-
//两个interface,判断日志等级
-
//warnlevel以下归到info日志
-
infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
-
return lvl < zapcore.WarnLevel
-
})
-
//warnlevel及以上归到warn日志
-
warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
-
return lvl >= zapcore.WarnLevel
-
})
-
-
infoWriter := getLogWriter("/data/liuhongdi/logs/zaplog2info")
-
warnWriter := getLogWriter("/data/liuhongdi/logs/zaplog2warn")
-
-
//创建zap.Core,for logger
-
core := zapcore.NewTee(
-
zapcore.NewCore(encoder, infoWriter, infoLevel),
-
zapcore.NewCore(encoder, warnWriter, warnLevel),
-
)
-
//生成Logger
-
logger := zap.New(core, zap.AddCaller())
-
sugarLogger = logger.Sugar()
-
}
-
-
//getEncoder
-
func getEncoder() zapcore.Encoder {
-
encoderConfig := zap.NewProductionEncoderConfig()
-
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
-
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
-
return zapcore.NewConsoleEncoder(encoderConfig)
-
}
-
-
//得到LogWriter
-
func getLogWriter(filePath string) zapcore.WriteSyncer {
-
warnIoWriter := getWriter(filePath)
-
return zapcore.AddSync(warnIoWriter)
-
}
-
-
-
//日志文件切割
-
func getWriter(filename string) io.Writer {
-
// 保存日志30天,每24小时分割一次日志
-
/*
-
hook, err := rotatelogs.New(
-
filename+"_%Y%m%d.log",
-
rotatelogs.WithLinkName(filename),
-
rotatelogs.WithMaxAge(time.Hour*24*30),
-
rotatelogs.WithRotationTime(time.Hour*24),
-
)
-
*/
-
//保存日志30天,每1分钟分割一次日志
-
hook, err := rotatelogs.New(
-
filename+"_%Y%m%d%H%M.log",
-
rotatelogs.WithLinkName(filename),
-
rotatelogs.WithMaxAge(time.Hour*24*30),
-
rotatelogs.WithRotationTime(time.Minute*1),
-
)
-
if err != nil {
-
panic(err)
-
}
-
return hook
-
}
四,测试效果
1,运行代码,控制台输出:
-
begin main
-
begin simpleHttpGet:www.cnblogs.com
-
begin simpleHttpGet:https://www.baidu.com
两个url地址中,第一个缺少协议,所以会生成错误日志,写到warn日志中,
另一个地址正确,会写到info日志中
2,查看日志文件内容:
-
root@ku:/data/liuhongdi/logs# more zaplog2warn_202011261853.log
-
2020-11-26T18:53:18.846+0800 ERROR zaplog2/main.go:29 Error fetching URL www.cnblogs.com : Error = Get "www.cnblogs.com": unsupported protocol schem
-
e ""
-
-
root@ku:/data/liuhongdi/logs# more zaplog2info_202011261853.log
-
2020-11-26T18:53:18.845+0800 DEBUG zaplog2/main.go:26 Trying to hit GET request for www.cnblogs.com
-
2020-11-26T18:53:18.846+0800 DEBUG zaplog2/main.go:26 Trying to hit GET request for https://www.baidu.com
-
2020-11-26T18:53:24.011+0800 INFO zaplog2/main.go:31 Success! statusCode = 200 OK for URL https://www.baidu.com
3,查看目录下的日志文件:
-
root@ku:/data/liuhongdi/logs# ls -l
-
总用量 8
-
lrwxrwxrwx 1 liuhongdi liuhongdi 49 11月 26 18:53 zaplog2info -> /data/liuhongdi/logs/zaplog2info_202011261853.log
-
-rw-r--r-- 1 liuhongdi liuhongdi 636 11月 26 18:53 zaplog2info_202011261853.log
-
lrwxrwxrwx 1 liuhongdi liuhongdi 49 11月 26 18:53 zaplog2warn -> /data/liuhongdi/logs/zaplog2warn_202011261853.log
-
-rw-r--r-- 1 liuhongdi liuhongdi 306 11月 26 18:53 zaplog2warn_202011261853.log
可以看到go-file-rotatelogs实现日志切分时是使用了linux的符号链接,
日志切分时,把当前写入的符号链接指向另一个日志文件即可
五,查看go.mod中的版本信息:
-
module github.com/liuhongdi/zaplog2
-
-
go 1.15
-
-
require (
-
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f // indirect
-
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
-
github.com/pkg/errors v0.9.1 // indirect
-
go.uber.org/multierr v1.6.0 // indirect
-
go.uber.org/zap v1.16.0 // indirect
-
)
posted on 2021-01-22 10:58 ExplorerMan 阅读(709) 评论(0) 编辑 收藏 举报