Nginx 日志滚动
Nginx 日志滚动配置
在linux下配置日志滚动一般都用系统自带的logrotate,但是在之前的使用中发现,如果一个daemon只打开一个日志文件写日志,在logroate的配置文件中使用copytruncate,会有少部分日志丢失。在对日志要求不是特别严格的情况下这是可行的,但有时候这丢失的几行日志很重要,就需要一个比较严格的日志滚动方法。
通过搜索找到一种不错的方法,不用kill nginx,而是使用apache的rotatelogs
** 安装apache,rotatelogs是apache自带的工具,配置日志目录**
mkdir -p /opt/nginx_logs
cp rotatelogs /opt/nginx_logs/
chmod +x /opt/nginx_logs/rotatelogs
** 创建命名管道**
mkdir /opt/nginx_logs/abc_www/
mkfifo /opt/nginx_logs/abc_www/access_log
** 配置nginx.conf,将access_log 指向命名管道**
access_log /opt/nginx_logs/abc_www/access_log main;
** 创建切割日志目录**
mkdir /opt/nginx_logs/abc_www/log/
** 日志切割脚本rotate.sh,用rotatelogs实现**
#!/bin/sh
baselogdir=/opt/nginx_logs/abc_www
rotatelogs=/opt/nginx_logs/rotatelogs
while [ 1 ]
do
echo `date +"%F %T"`" rotatelogs access start"
$rotatelogs $baselogdir/log/access_%Y%m%d-%H%M%S.log 5M 480 < $baselogdir/access_log
echo `date +"%F %T"`" rotatelogs access stop"
sleep 1;
done
按照5M的大小切割文件 在实际应用中这个值应该设置得比较大,如果需要一天一个日志文件的话5M 改为 86400 = 24 * 60 * 60,也就是一天的秒数
** 启动脚本run.sh**
#!/bin/sh
sh /opt/nginx_logs/abc_www/rotate.sh >> /opt/nginx_logs/abc_www/log/access-rotate.log 2>&1 &
** 测试,使用ab工具测试**
ab -n 100000 -c 1000 "http://localhost/"
##############################
-rw-r--r--. 1 root root 5245560 Apr 11 22:54 access_20150411-225410.log
-rw-r--r--. 1 root root 4251582 Apr 11 22:54 access_20150411-225427.log
-rw-r--r--. 1 root root 5245615 Apr 11 23:10 access_20150411-231035.log
-rw-r--r--. 1 root root 4254385 Apr 11 23:11 access_20150411-231048.log
nginx配置错误检查 另外在测试过程中发现error.log也在不断的增大,都是“Too many open files”错误 进行如下检查:
- 检查nginx能打开的文件数
ps ax | grep nginx 36756 ? Ss 0:00 nginx: master process nginx 36757 ? S 0:08 nginx: worker process 列出nginx的worker进程,然后 cat /proc/XXX/limits,其中XXX是worker进程的进程号,找到如下是行:
Max open files 1024 4096 files
- 检查系统打开文件数
sysctl -a | grep file-max fs.file-max = 98684 系统默认值,这个值比较大暂时不修改
通过检查发现系统能打开的文件数很大,但每个进程的文件数只有1024,这个可以用ulimit -n来确认
错误修复 因此需要修改配置来实现nginx的文件打开数
- 在nginx.conf中增加如下行
worker_rlimit_nofile 15360;
- 修改/etc/security/limits.conf,增加如下两行
soft nofile 10240hard nofile 15360
- 重启nginx,需要将master也停掉,不能时候用kill -HUP,然后再查看worker进程的Max open files
Max open files 15360 15360 files
修改成功,在测试时没有再报“Too many open files”
参考: nginx日志按照天进行分割