您的位置:首页 > 运维架构 > Nginx

centOS 6 使用logrotate归档 nginx大日志

2018-01-15 00:00 495 查看
摘要: centOS 6 使用logrotate归档 nginx大日志

linux环境下log等增量文件切割压缩,阿里云时不时报警,在忍了n次以后,忍无可忍,遂发现logrotate

优点:
1、linux市面主流发行版本都自带logrotate
2、配置简单
缺点
centos5和centos6+的logrotate是不同的实现方式,网上内容都是copy的,原创不多,新手容易入坑,5和6+对应着crontab与anacron的区别就不展开叙述,前者是普通定时任务,后者可以认为是自带续命功能的定时任务(每分钟扫描是否满足条件,比如说意外断电影响执行开机后会立刻执行)
如图



以CentOS Linux release 7.3.1611为例
STEP 1: 追加配置文件
在/etc/logrotate.d追加文件
例如压缩nginx访问日志的文件:nginx
个人配置:

nginx log file path: /var/log/nginx/host.access.log
nginx pid file path: /usr/local/nginx/logs/nginx.pid

/var/log/nginx/host.access.log {
daily
missingok
rotate 30
compress
#delaycompress #延迟一天归档
notifempty
create 600 root root
sharedscripts
postrotate
if [ -f /usr/local/nginx/logs/nginx.pid ]; then
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
fi
endscript
}


STEP 2: 测试

logrotate -vfd /etc/logrotate.d/nginx

-v 显示详情
-f 强制分割日志
-d 调试配置,结果输出,不进行真实分割操作
STEP 3:
选择1或者2
1、重复STEP 2,去掉-d debug

logrotate -vf /etc/logrotate.d/nginx

2、等待一天第二天查看效果
STEP 4:
STEP 3 完成后你会发现,有一些问题。日志是第二天3点左右归档,下面可能是你的/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

以上anacrontab配置文件最重要的是最后一部分,以这行为例:
1 5 cron.daily nice run-parts /etc/cron.daily

表示每天都执行/etc/cront.daily/目录下的脚本文件,真实的延迟是RANDOM_DELAY+delay。这里的延迟是5分钟,加上上面的RANDOM_DELAY,所以实际的延迟时间是5-50之间,开始时间为03-22点,如果机器没关,那么一般就是在03:05-03:50之间执行。nice命令将该进程设置为nice=10,默认为0,即低优先级进程。如果RANDOM_DELAY=0,那么表示准确延迟5min,即03:05执行cron.daily内的脚本。

所以做一下修改
执行任务时间为23时内
START_HOURS_RANGE=23-23
最大延迟9分钟
RANDOM_DELAY=9
默认从50分钟开始
1 50 cron.daily nice run-parts /etc/cron.daily

即可在每天的23:50-23:59分归档你的日志文件

注意:有个坏处就是你更改了anacron的主配置文件,得确保对其他的任务无影响,才可修改

references: https://www.thegeekstuff.com/2011/05/anacron-examples/ http://blog.51cto.com/colynn/1441436 https://www.52os.net/articles/using-logrotate-manage-tomcat-logs.html http://blog.csdn.net/damiaomiao666/article/details/72597731
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  logrotate anacron centOS6