很多软件在运行时都会产生随机日志,这些日志如果不经常清理会导致程序文件日积月累非常大,导致程序往大文件中写入日志变得很困难,打开文件也非常困难,所以我们有必要进行日志文件的切割,有利于实际操作中阅读日志文件,查看问题!
以下为切割Nginx运行日志教程,利用Linux系统自带Logrotate工具进行切割!
Logrotate的介绍
显而易见,Logrotate是基于CRON来运行的,其脚本是「/etc/cron.daily/logrotate」:
#!/bin/sh
/usr/sbin/logrotate /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0
实际运行时,Logrotate会调用配置文件「/etc/logrotate.conf」:
# see "man logrotate" for details
# rotate log files weekly
weekly
# keep 4 weeks worth of backlogs
rotate 4
# create new (empty) log files after rotating old ones
create
# uncomment this if you want your log files compressed
#compress
# RPM packages drop log rotation information into this directory
include /etc/logrotate.d
# no packages own wtmp -- we'll rotate them here
/var/log/wtmp {
monthly
minsize 1M
create 0664 root utmp
rotate 1
}
# system-specific logs may be also be configured here.
这里的设置可以理解为Logrotate的缺省值,当然了,可以我们在「/etc/logrotate.d」目录里放置自己的配置文件,用来覆盖Logrotate的缺省值。
Logrotate的演示
按天保存一周的Nginx日志压缩文件,配置文件为「/etc/logrotate.d/nginx」:
/usr/local/nginx/logs/*.log {
daily
dateext
compress
rotate 7
sharedscripts
postrotate
kill -USR1 `cat /var/run/nginx.pid`
endscript
}
如果你等不及CRON,可以通过如下命令来手动执行:
shell> logrotate -f /etc/logrotate.d/nginx
当然,正式执行前最好通过Debug选项来验证一下,这对调试也很重要:
shell> logrotate -d -f /etc/logrotate.d/nginx
(资源库 www.zyku.net)