CentOS Linux使用logrotate分割管理日志

logrotate程序是一个日志文件管理工具。用于分割日志文件,删除旧的日志文件,并创建新的日志文件,起到“转储”作用。可以节省磁盘空间。

logrotate命令格式:
logrotate [OPTION…] <configfile>
-d, –debug :debug模式,测试配置文件是否有错误。
-f, –force :强制转储文件。
-m, –mail=command :发送日志到指定邮箱。
-s, –state=statefile :使用指定的状态文件。
-v, –verbose :显示转储过程。

logrotate的配置文件是/etc/logrotate.conf。查看缺省配置情况:

cat /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.

简单说明:
weekly :所有的日志文件每周转储一次。
rotate 4 :转储的文件分为4份。
create :logrotate自动创建新的日志文件。
compress :压缩日志文件。默认是注释掉的。
include /etc/logrotate.d :读入/etc/logrotate.d目录下的日志转储参数,当系统中安装了RPM软件包时,RPM包的日志转储参数一般会自动建立在/etc/logrotate.d目录下。
/var/log/wtmp段 :对/var/log/wtmp日志转储的配置。

使用logrotate管理lnmp一键安装包中nginx的连接日志,lnmp日志文件在/home/wwwlogs目录下。

建立配置文件:

vim /etc/logrotate.d/nginx

输入如下:

/home/wwwlogs/access.log /home/wwwlogs/nginx_error.log {
notifempty
daily
rotate 5
sharedscripts
postrotate
/bin/kill -HUP `/bin/cat /usr/local/nginx/logs/nginx.pid`
endscript
}

说明:
notifempty :如果是空文件的话,不转储。
daily :日志文件每天转储一次。
rotate 5 ;转储文件分为5份。
postrotate/endscript :日志转储后执行的脚本。这里用来让nginx重新生成日志文件。nginx.pid里存的是nginx的主进程号。

执行logrotate:

/usr/sbin/logrotate -vf /etc/logrotate.conf

如果没有报错,生成了转储文件,nginx正常访问,就OK了。

logrotate如何自动执行:
在/etc/cron.daily目录下有logrotate执行的脚本。通过crontab程序每天执行一次。

参考资料:
http://blog.csdn.net/cjwid/article/details/1690101
http://hi.baidu.com/daizhongxian/blog/item/be0879dd3133fbd48c1029d0.html

《CentOS Linux使用logrotate分割管理日志》上的一个想法

评论已关闭。