日志切割之Logrotate
简介
Linux系统默认安装logrotate工具,它默认的配置文件在:
/etc/logrotate.conf
/etc/logrotate.d/
logrotate.conf 才主要的配置文件,logrotate.d 是一个目录,该目录里的所有文件都会被主动的读入/etc/logrotate.conf中执行。
另外,如果 /etc/logrotate.d/ 里面的文件中没有设定一些细节,则会以/etc/logrotate.conf这个文件的设定来作为默认值。
Logrotate是基于CRON来运行的,其脚本是/etc/cron.daily/logrotate,日志轮转是系统自动完成的。
实际运行时,Logrotate会调用配置文件/etc/logrotate.conf。
可以在/etc/logrotate.d目录里放置自定义好的配置文件,用来覆盖Logrotate的缺省值。
#!/bin/sh
/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0
如果等不及cron自动执行日志轮转,想手动强制切割日志,需要加-f参数;不过正式执行前最好通过Debug选项来验证一下(-d参数),这对调试也很重要
/usr/sbin/logrotate -f /etc/logrotate.d/nginx
/usr/sbin/logrotate -d -f /etc/logrotate.d/nginx
logrotate命令格式:
logrotate [OPTION...] <configfile>
-d, --debug :debug模式,测试配置文件是否有错误。
-f, --force :强制转储文件。
-m, --mail=command :压缩日志后,发送日志到指定邮箱。
-s, --state=statefile :使用指定的状态文件。
-v, --verbose :显示转储过程。
根据日志切割设置进行操作,并显示详细信息
/usr/sbin/logrotate -v /etc/logrotate.conf
/usr/sbin/logrotate -v /etc/logrotate.d/php
根据日志切割设置进行执行,并显示详细信息,但是不进行具体操作,debug模式
/usr/sbin/logrotate -d /etc/logrotate.conf
/usr/sbin/logrotate -d /etc/logrotate.d/nginx
查看各log文件的具体执行情况
cat /var/lib/logrotate.status
注意问题
问题一:要在linux下创建配置文件
否则会因为文件权限问题报错
error: Ignoring 文件路径 because it is writable by group or others.
问题二:因为切割日志文件目录权限问题,需要在配置文件添加
su 用户 用户组 例如: su root root
error: skipping "日志文件路径" because parent directory has insecure permissions (It's world writable or writable by group which is not "root") Set "su" directive in config file to tell logrotate which user/group should be used for rotation.