Linux自带的logrotate程序来解决catalina.out的日志轮转问题.md

  • 1.首先编辑logrotate.conf文件,打开compress选项(去掉注释)
[root@localhost ~]#  cat /etc/logrotate.conf | grep -v "^$"| grep -v "#"
weekly
rotate 4
create
compress
include /etc/logrotate.d
  • 2.添加指定文件,在/etc/logrotate.d/目录下新建一个名为tomcat的文件
[root@localhost ~]# cat > /etc/logrotate.d/tomcat <<EOF
/home/tomcat/utr/logs/catalina.out{ #要轮转的文件
    copytruncate    # 创建新的catalina.out副本后,截断源catalina.out文件
    daily    # 每天进行catalina.out文件的轮转
    rotate 7     # 至多保留7个副本
    missingok    # 如果要轮转的文件丢失了,继续轮转而不报错
    compress     # 使用压缩的方式(节省硬盘空间;一个2~3GB的日志文件可以压缩成60MB左右)
    size 16M     # 当catalina.out文件大于16MB时,就轮转
    dateext
    dateformat .%Y-%m-%d
    extension .log
    notifempty
}
EOF

参数说明:
copytruncate #备份日志并截断源文件
nocopytruncate # 备份日志文件不截断
dateext #使用当期日期作为命名格式
notifempty #当日志文件为空时,不进行轮转
daily # 每天进行文件的轮转
size 16M # 当文件大于16MB时,就会轮转
rotate 30 #指定日志文件删除之前转储的次数

  • 3.执行方式
    ①自动执行原理

    1.每天晚上crond守护进程会运行在/etc/cron.daily目录中的任务列表;
    2.与logrotate相关的脚本也在/etc/cron.daily目录中。运行的方式为"/usr/bin/logrotate /etc/logrotate.conf";
    3./etc/logrotate.conf文件include了/etc/logrotate.d/目录下的所有文件。还包括我们上面刚创建的tomcat文件;
    4./etc/logrotate.d/tomcat文件会触发/usr/local/apache-tomcat-8.0.28/logs/catalina.out文件的轮转。

    ②手动执行:logrotate /etc/logrotate.conf

    ③只轮转刚刚的tomcat配置文件:logrotate --force /etc/logrotate.d/tomcat

  • 3.自动执行时间

[root@localhost ~]# cat /etc/anacrontab
# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=45
# the jobs will be started during the following hours only
START_HOURS_RANGE=3-22

#period in days   delay in minutes   job-identifier   command
1	5	cron.daily		nice run-parts /etc/cron.daily
7	25	cron.weekly		nice run-parts /etc/cron.weekly
@monthly 45	cron.monthly		nice run-parts /etc/cron.monthly

里面有个
START_HOURS_RANGE=3-22 这个是开始时间
RANDOM_DELAY=45 这个是随机的延迟时间,表示最大45min.

还有个
1 5 cron.daily nice run-parts /etc/cron.daily
第一个是Recurrence period 第二个是延迟时间,所以cron.daily会在3:22+(5,45)这个时间段执行,/etc/cron.daily是个文件夹

参考文献

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章