Shell script splits Nginx logs and cleans them regularly [without restarting nginx]

I wrote an article about shell script splitting Nginx logs and cleaning them regularly, link: http://www.webyang.net/Html/web/article_255.html but need to reload nginx, some people have a psychological shadow on restarting nginx , so I changed it again:

 

  1. #!/bin/bash
  2. #nginx access log segmentation shell script
  3. #log directory
  4. log_dir="/usr/local/nginx/logs/"
  5. cd $ log_dir
  6. time=`date +%Y%m%d --date="-1 day"`
  7. #Hisashi preservation heaven number
  8. save_days=15
  9. #The position of the log file name is divided by '/', key('/' number + 1)
  10. num = 6 ;
  11.  
  12. #To be optimized here (get the file name without a suffix)
  13. website=`ls $log_dir*.log | xargs -n 1 | cut -f 1 -d "." | cut -f $num -d "/"`
  14. #All log files in the log directory are folders, and the corresponding time files will be created cyclically
  15. for i in $website
  16. do
  17. #Check if the directory exists
  18. if[!-d $log_dir$i ];then
  19. mkdir "$i"
  20. be
  21.  
  22. cp $log_dir$i.log $log_dir$i/$i-$time.log
  23. true>$log_dir$i.log
  24. done
  25.  
  26. find $log_dir -mtime +$save_days -exec rm -rf {} \;

Set up crontab to run once every morning.


展示: web1.log => web1/web1-20160322.log web1/web1-20160323.log web2.log => web2/web2-20160322.log web2/web2-20160323.log

 

There are other methods such as cronolog, logrotate, etc., you can refer to: http://www.tuicool.com/articles/BF36rq

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326939729&siteId=291194637