golang之log rotate详解
操作系统:CentOS6.9_x64
go语言版本:1.8.3
问题描述
golang的log模块提供的有写日志功能,示例代码如下:
/*
golanglogexample
*/
packagemain
import(
"log"
"os"
)
funcmain(){
logFile,err:=os.Create("test1.log")
deferlogFile.Close()
iferr!=nil{
log.Fatalln("openfileerror!")
}
logger:=log.New(logFile,"[Debug]",log.Ldate|log.Ltime|log.Lshortfile)
logger.Println("testdebugmessage")
logger.SetPrefix("[Info]")
logger.Println("testinfomessage")
}
运行效果:
[root@localt2]#gobuildlogTest1.go [root@localt2]#./logTest1 [root@localt2]#cattest1.log [Debug]2017/06/1323:18:36logTest1.go:19:testdebugmessage [Info]2017/06/1323:18:36logTest1.go:21:testinfomessage [root@localt2]#
go语言的log模块没有提供logrotate接口,但实际开发中我们需要该功能:
我们不希望单个日志过大,否则文本编辑器无法打开,查看比较困难;
更不希望占用太大的存储空间,可以指定最多存多少个日志文件。
解决方案
借助带缓冲的channel来实现。
示例代码如下:
/*
golanglogrotateexample
*/
packagemain
import(
"fmt"
"log"
"os"
"time"
)
const(
BACKUP_COUNT=5
MAX_FILE_BYTES=2*1024
)
funcdoRotate(fPrefixstring){
forj:=BACKUP_COUNT;j>=1;j--{
curFileName:=fmt.Sprintf("%s_%d.log",fPrefix,j)
k:=j-1
preFileName:=fmt.Sprintf("%s_%d.log",fPrefix,k)
ifk==0{
preFileName=fmt.Sprintf("%s.log",fPrefix)
}
_,err:=os.Stat(curFileName)
iferr==nil{
os.Remove(curFileName)
fmt.Println("remove:",curFileName)
}
_,err=os.Stat(preFileName)
iferr==nil{
fmt.Println("rename:",preFileName,"=>",curFileName)
err=os.Rename(preFileName,curFileName)
iferr!=nil{
fmt.Println(err)
}
}
}
}
funcNewLogger(fPrefixstring)(*log.Logger,*os.File){
varlogger*log.Logger
fileName:=fmt.Sprintf("%s.log",fPrefix)
fmt.Println("fileName:",fileName)
logFile,err:=os.OpenFile(fileName,os.O_RDWR|os.O_CREATE|os.O_APPEND,0666)
iferr!=nil{
fmt.Println("openfileerror!")
}else{
logger=log.New(logFile,"[Debug]",log.Ldate|log.Ltime|log.Lshortfile)
}
returnlogger,logFile
}
funclogWorker(msgQueue<-chanstring){
fPrefix:="msg"
logger,logFile:=NewLogger(fPrefix)
formsg:=rangemsgQueue{
logger.Println(msg)
fi,err2:=logFile.Stat()
iferr2==nil{
iffi.Size()>MAX_FILE_BYTES{
logFile.Close()
doRotate(fPrefix)
logger,logFile=NewLogger(fPrefix)
}
}
}
logFile.Close()
}
funcmain(){
msgQueue:=make(chanstring,1000)
gologWorker(msgQueue)
forj:=1;j<=1000;j++{
msgQueue<-fmt.Sprintf("msg_%d",j)
time.Sleep(1*time.Second)
}
close(msgQueue)
return
}
运行效果如下:
[root@localt2]#./logRotateTest1 fileName:msg.log rename:msg.log=>msg_1.log fileName:msg.log rename:msg_1.log=>msg_2.log rename:msg.log=>msg_1.log fileName:msg.log rename:msg_2.log=>msg_3.log rename:msg_1.log=>msg_2.log rename:msg.log=>msg_1.log fileName:msg.log ^C
讨论
这里只是个简单的示例代码,实现了logrotate,更多功能需自行开发。
好,就这些了,希望对你有帮助。
以上这篇golang之logrotate详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。