在CentOS系统中,使用Golang编写的应用程序可以通过配置日志库来实现日志轮转。常用的日志库有logrus、zap等。这里以logrus为例,介绍如何设置日志轮转。
首先,确保已经安装了logrus库:
go get github.com/sirupsen/logrus
接下来,创建一个名为main.go的文件,并编写以下代码:
package main
import (
"github.com/sirupsen/logrus"
"os"
"time"
)
func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetOutput(os.Stdout)
logrus.SetReportCaller(true)
log := logrus.NewEntry(logrus.New())
// 设置日志轮转
log.Info("Starting log rotation test...")
for {
log.Info("This is a test log entry")
time.Sleep(1 * time.Second)
}
}
现在,我们需要使用logrus的SetOutput方法将日志输出到一个支持轮转的文件中。为此,我们可以使用lumberjack库:
go get gopkg.in/natefinch/lumberjack.v2
然后,修改main.go文件,将日志输出到lumberjack.Logger:
package main
import (
"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
"os"
"time"
)
func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetReportCaller(true)
log := logrus.NewEntry(logrus.New())
// 设置日志轮转
log.Info("Starting log rotation test...")
// 配置lumberjack.Logger
lumberjackLogger := &lumberjack.Logger{
Filename: "/var/log/myapp.log", // 日志文件路径
MaxSize: 1, // 每个日志文件的最大大小(单位:MB)
MaxBackups: 3, // 保留的最大日志文件数量
MaxAge: 28, // 保留的最大日志文件天数
Compress: true, // 是否压缩旧日志文件
}
logrus.SetOutput(lumberjackLogger)
for {
log.Info("This is a test log entry")
time.Sleep(1 * time.Second)
}
}
现在,运行main.go文件:
go run main.go
这将在/var/log/myapp.log文件中生成日志,并根据配置进行轮转。你可以根据需要调整lumberjack.Logger的参数。
如果你使用的是其他日志库,如zap,可以查找相应的轮转日志库并进行类似的配置。