欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

nginx日志切割脚本分享

程序员文章站 2023-01-08 17:35:14
实现方法一 #!/bin/bash logs_path="/data/application/nginx/logs" pid_path="/data/appl...

实现方法一

#!/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

实现方法二

试验环境:

# cat /etc/redhat-release 
red hat enterprise linux server release 5.3 (tikanga)

# /opt/nginx/nginx -v
nginx version: nginx/1.6.2

代码:

#!/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