实现方法一

1
2
3
4
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
三十
31
32
33
34
35
#!/bin/bash
logs_path= "/data/application/nginx/logs"
pid_path= "/data/application/nginx/nginx.pid"
month=` date +%y-%m`
date =` date +%y-%m-%d`
time =` date +%h`
waittime=$((24*60*60))
 
logcut()
{
   cd $logs_path
   mkdir -p $month
   while true
   do
     mv $logs_path /access .log $logs_path/$month /access_ $ date .log
     kill -usr1 ` cat ${pid_path}`
   done
   sleep $waittime
   return 0
}
 
case $1  in
start)
     logcut > /dev/null &
     ;;
stop)
     kill -9 ` ps aux |  grep logcut |  grep - v grep awk '{print $2}' `> /dev/null
     ;;
restart)
     kill -9 ` ps aux |  grep logcut |  grep - v grep awk '{print $2}' `> /dev/null
     logcut > /dev/null &
     ;;
*)
     echo "usage error!please use " start " or " stop " or " restart "!"
esac

实现方法二

试验环境:

1
2
3
4
# cat /etc/redhat-release
red hat enterprise linux server release 5.3 (tikanga)
 
# /opt/nginx/nginx -v
nginx version: nginx /1 .6.2

代码:

1
2
3
4
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
三十
31
32
33
#!/bin/bash
# ==============================================================================
# chmod u+x /opt/nginx/cut_nginx_log.sh
# crontab -e
# 0 0 * * * /opt/nginx/cut_nginx_log.sh > /opt/nginx/logs/cut_nginx_log.log 2>&1
# ==============================================================================
 
logs_path= "/opt/nginx/logs"
archive_year=$( date -d  "yesterday" "+%y" )
archive_month=$( date -d  "yesterday" "+%m" )
archive_date=$( date -d  "yesterday" "+%y%m%d_%h%m%s" )
if [ -r  /opt/nginx/nginx .pid ];  then
   mkdir -p  "${logs_path}/${archive_year}/${archive_month}"
   mv "${logs_path}/access.log" "${logs_path}/${archive_year}/${archive_month}/access_${archive_date}.log"
   kill -usr1 $( cat "/opt/nginx/nginx.pid" )
   sleep 1
   gzip "${logs_path}/${archive_year}/${archive_month}/access_${archive_date}.log"
else
   echo "nginx might be down"
fi
 
# ==============================================================================
# clean up log files older than 100 days
# ==============================================================================
 
# change housekeeping=1 to enable clean up
housekeeping=0
keep_days=100
if [ $housekeeping == 1 ];  then
   if [ -d  "${logs_path}" ];  then
     find "${logs_path}" - type f -name  "access_*.log.gz" -mtime +${keep_days} - exec rm -f {} \;
   fi
fi

参考:http
//wiki.nginx.org/logrotation