系统时时刻刻都在产生日志,如果不及时清理,很快就会灌满硬盘,但如果要手工清理,又很麻烦。
这种情况下,logrotate 这个程序很好的完成这个任务。
logrotate 用来把旧的日志文件删除,并创建新的日志文件,我们把它叫做“转储”。
我们可以根据日志文件的大小,也可以根据其天数来转储,这个过程一般通过一个叫做crond的守护进程来执行,logrotate 还可以用于压缩日志文件,以及发送日志到指定的E-mail 。
logrotate 的配置文件是 /etc/logrotate.conf。
查看当前版本
在系统中使用命令来查看版本:
logrotate --version
一些使用的方法,请参考下面的内容:
查看使用手册
man logrotate
nginx 日志归档
在默认情况下,操作系统已经为我们配置了 nginx 的默认日志归档。
归档的配置文件为: /etc/logrotate.d/nginx
可以直接编辑这个文件。
/var/log/nginx/*.log
/var/log/nginx/src.isharkfly.com/*.log
{
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
prerotate
if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
run-parts /etc/logrotate.d/httpd-prerotate; \
fi \
endscript
postrotate
invoke-rc.d nginx rotate >/dev/null 2>&1
endscript
}
对我们来说,我们虚拟主机的日志和 nginx 的日志在相同的目录下,只是在下面添加了一个文件夹。
所以,我们就在上面添加文件夹就行。
归档测试
配置文件完成修改后,可以对配置进行测试:
运行命令:
logrotate /etc/logrotate.d/nginx --debug
服务器上输出的内容为:
root@ns564012:/etc/logrotate.d# logrotate /etc/logrotate.d/nginx --debug
warning: logrotate in debug mode does nothing except printing debug messages! Consider using verbose mode (-v) instead if this is not what you want.
reading config file /etc/logrotate.d/nginx
Reading state from file: /var/lib/logrotate/status
Allocating hash table for state file, size 64 entries
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Creating new state
Handling 1 logs
rotating pattern: /var/log/nginx/*.log
/var/log/nginx/src.isharkfly.com/*.log
after 1 days (14 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/nginx/access.log
Now: 2025-02-06 02:38
Last rotated at 2025-02-06 00:00
log does not need rotating (log has been rotated at 2025-02-06 00:00, which is less than a day ago)
considering log /var/log/nginx/error.log
Now: 2025-02-06 02:38
Last rotated at 2025-02-06 00:00
log does not need rotating (log has been rotated at 2025-02-06 00:00, which is less than a day ago)
considering log /var/log/nginx/src.isharkfly.com/access.log
Creating new state
Now: 2025-02-06 02:38
Last rotated at 2025-02-06 02:00
log does not need rotating (log has already been rotated)
considering log /var/log/nginx/src.isharkfly.com/error.log
Creating new state
Now: 2025-02-06 02:38
Last rotated at 2025-02-06 02:00
log does not need rotating (log has already been rotated)
not running prerotate script, since no logs will be rotated
not running postrotate script, s
对我们来说,只需要日志进行归档就行,因为我们不希望日志内容占用过多的磁盘空间。