linux中的日志分割
1.问题背景,nginx日志过大不好删除
[root@localhost cron.daily]# cd /lk/nginx/log/
[root@localhost log]# ll
总用量 2386188
-rw-r--r--. 1 root root 2078699697 5月 9 13:02 access.log
-rw-r--r--. 1 root root 11138 5月 6 10:28 error.log
[root@localhost log]# du -sh *
2.3G access.log
12K error.log
[root@localhost log]# pwd
/lk/nginx/log
[root@localhost log]#
2,要求:日志只保留7天,按天分割
3,实现步骤
1,安装软件
yun -y install crond && systemctl restart crond && systemctl enable crond
2,创建日志切割配置
vi /etc/logrotate.d/nginx
/lk/nginx/log/access.log {
daily
rotate 4
missingok
compress
delaycompress
notifempty
create 0640 root root
dateext
dateformat -%Y%m%d
}
3,测试配置
sudo logrotate -d /etc/logrotate.d/nginx
这将模拟日志切割,且不会实际修改文件。如果配置正确且没有错误,你可以去掉 -d
参数,执行实际的日志切割:-f 强制切割
sudo sudo logrotate -f /etc/logrotate.d/nginx
4. 自动化
设置时间
crontab -e
59 23 * * * /usr/sbin/logrotate -f /etc/logrotate.d/nginx
这表示 logrotate
会在每天在 23:59 自动执行日志轮转
确保 Cron 服务正在运行
sudo systemctl status crond && systemctl restart crond