当前位置首页 > Nginx知识

关于使用logrotate对tomcat和nginx日志进行滚动的注意事项

阅读次数:344 次  来源:admin  发布时间:

几个细节

1、使用logrotate自动处理日志时,不需要手动添加 corn 任务

因为logroate本身就存在一条 corn 任务:

[root@xxx]# cat /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 $EXITVALUE

每天都会执行一次这个脚本,其中的 /etc/logrotate.conf 就是 logrotate 的主配置文件,看看它的内容:

[root@xxx ~]# 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

# use date as a suffix of the rotated file
dateext

# uncomment this if you want your log files compressed
#compress

# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

# system-specific logs may be also be configured here.

注意这行代码:include /etc/logrotate.d,意思就是每次都自动执行这个目录下的子配置文件。

所以 logrotate 自带的,或者我们手动创建的滚动脚本都会自动执行,除非需要明确具体执行的时间,否则就无需再手动创建 corn 计划任务。

2、滚动模式:create(新建模式,默认)/ copytruncate(复制模式)

两种模式的区别:

create:先把当前使用的日志文件重命名(存档),再创建一个新的日志文件继续记录;

copytruncate:一直使用当前的日志文件,每次滚动时将历史信息剪切到一个新的日志文件中(存档),使得当前的日志文件只保留最新的日志信息。

这两种模式是互斥的,主要区别就是对当前日志的切换处理,第一种需要切换到新的日志文件继续写入,第二种一直在向同一个日志文件写入,因此不涉及切换日志的问题。

性能方面,如果每天生成的日志非常大,那么肯定第一种性能更好,否则影响不大。

可靠性方面,由于复制模式在实际操作时有丢失部分数据的风险,因此应优先使用默认的 create 模式。

经过实际测试:tomcat8053不支持 create 模式,每次运行后都无法启动,具体原因不明,tomcat其他版本未测试。

正在使用的滚动脚本

1、tomcat

[root@xxx ~]# cat /etc/logrotate.d/tomcat
/mnt/runtime/tomcat/tomcat8053/logs/catalina.out {
    copytruncate
    daily
    rotate 15
    missingok
    notifempty
    dateext
    compress
    delaycompress
}

上面说过,tomcat 不支持默认的 create 模式,因此必须手动指定 copytruncate 模式。

2、nginx

[root@xxx ~]# cat /etc/logrotate.d/nginx
/mnt/logs/nginx/*log {
    create 0664 nginx root
    daily
    dateext
    rotate 10
    missingok
    notifempty
    compress
    sharedscripts
    postrotate
        /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}

logrotate 的 /etc/logrotate.d 目录下,默认就有一个关于 nginx 的滚动脚本,不需要手动创建。

只需要改动其中nginx日志的实际位置,同时增加一个 dateext(用日期命名,否则默认使用序号) 参数就可以了。

ginx支持 create 模式,因此在每次滚动脚本执行后,都需要更新PID来定位新的日志文件。

手动执行 logrotate :

logrotate -vf /etc/logrotate.d/tomcat
上一篇:IIS7.0Appcmd命令详解
下一篇:IIS的0x8ffe2740问题解决