Home >Backend Development >PHP Tutorial >Shell script splits Nginx logs and cleans them regularly
By default, nginx will only generate one access log. With daily accumulation, the log file will become very large. If you need to analyze the log, it is not convenient to use script analysis or download the log for local analysis. Splitting Nginx's access logs every day is helpful for analyzing the logs.
1: Create a new script file
vim cut_nginx_log.sh<ol> <li value="1"><span>#!/bin/bash</span></li> <li><span>#nginx access log segmentation shell script</span></li> <li><span>#www.webyang.net</span></li> <li><span>#日志目录</span></li> <li> <span>log_dir</span><span>=</span><span>"/usr/local/nginx/logs/"</span> </li> <li><span>cd $log_dir</span></li> <li> <span>time</span><span>=</span><span>`date +%Y%m%d --date="-1 day"`</span> </li> <li><span>#nginx启动目录</span></li> <li> <span>nginx_dir</span><span>=</span><span>"/etc/init.d/nginx"</span> </li> <li><span>#日志保存天数</span></li> <li> <span>save_days</span><span>=</span><span>15</span> </li> <li><span>#日志文件名所处'/'分割的位置,key('/'数+1)</span></li> <li> <span>num</span><span>=</span><span>6</span><span>;</span> </li> <li><span> </span></li> <li><span>#此处待优化(取得文件不带后缀的文件名)</span></li> <li> <span>website</span><span>=</span><span>`ls $log_dir*.log | xargs -n 1 | cut -f 1 -d "." | cut -f $num -d "/"`</span> </li> <li><span>#日志目录下所有的日志文件为文件夹,循环新建对应的时间文件</span></li> <li> <span>for</span><span> i </span><span>in</span><span> $website</span> </li> <li><span>do</span></li> <li><span>#判断目录是否存在</span></li> <li> <span>if</span><span>[</span><span>!</span><span>-</span><span>d $log_dir$i </span><span>];</span><span>then</span> </li> <li> <span> mkdir </span><span>"$i"</span> </li> <li><span>fi</span></li> <li> <span> mv $log_dir$i</span><span>.</span><span>log $log_dir$i</span><span>/</span><span>$i</span><span>-</span><span>$time</span><span>.</span><span>log</span> </li> <li><span>done</span></li> <li><span> </span></li> <li><span>#删除设置天数前的数据</span></li> <li> <span>find $log_dir</span><span>/</span><span>-</span><span>mtime </span><span>+</span><span>$save_days </span><span>-</span><span>exec</span><span> rm </span><span>-</span><span>rf </span><span>{}</span><span> \;</span> </li> <li><span> </span></li> <li><span>#平滑启动nginx</span></li> <li><span>$nginx_dir reload</span></li> </ol>2. Set up crontab and cut regularly every day. If it is not installed, run yum -y install crontabs to install it.
web1.log => web1/web1-20160322.log
web1/web1-20160323.logweb2.log => web2/web2-20160322.log
web2/web2-20160323. log