测试环境:Ubuntu20.04 LTS 64Bit
对于logrotate的详细介绍及其使用,网上有很多的资料可给你提供参考,所以这篇文章不打算写这些。如果你想快速验证自定义的logrotate配置文件按自定义时间执行,那么不妨看看这篇文章。
注意, 以下所有命令都是在root权限下执行。
一、准备工作
# mkdir /var/test_log/
# cd /var/test_log/
# head -c 10M < /dev/urandom > ./test.log #创建一个日志文件并在填入一个10MB的随机比特流数据。
# ls -lh ./test.log #查看大小
# mkdir /etc/logrotate.daily.test/
# cd /etc/logrotate.daily.test/
# touch test_logrotate #创建自定义logrotate配置文件
# vim test_logrotate
二、编写logrotate配置文件test_logrotate,其内容如下:
/var/test_log/*.log {
rotate 3
daily
missingok
notifempty
compress
delaycompress
sharedscripts
}
三、添加crontab计划任务,按自定义时间执行上面的logrotate配置文件
# crontab -e
执行crontab -e命令后,然后在里面添加如下内容:
*/1 * * * * /usr/sbin/logrotate -vf /etc/logrotate.daily.test/test_logrotate
最终效果如下:
保存退出后,如果看到如下图所示,则内容添加成功。否则需要再次执行crontab -e之后的相关操作。
四、重启crontab,这一步可能不是必须的,但为了保证得到期望的结果,还是执行一下吧。
# systemctl restart cron
五、结果
重启contab服务后,等一分钟以上,我们就可以得到转储文件,如下图所示:
每次文件被转储后,再创建一个新的test.log文件,看看其效果如何。这一步可多重复几次,好好体会一下logrotate的强大功能。
# head -c 10M < /dev/urandom > ./test.log #创建一个日志文件并在填入一个10MB的随机比特流数据。