linux crontab nginx 日志分割,压缩,删除旧日志bash脚本

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hknaruto/article/details/86368675

脚本

#!/bin/bash

# 由crontab每天0点分割并压缩备份日志,超过备份数量限制的,按照时间排序删除
# 0点,先处理昨天的日志,分割,然后压缩前天的日志
# crontab -e
# 0 0 * * * sh -x cut_nginx_log.sh >> /root/cron_task/logs/cut_nginx_log.log 2>&1
# :wq
# systemctl reload crond
NGINX_INSTALL_PATH="/usr/local/nginx"
NGINX_LOG_PATH=$NGINX_INSTALL_PATH"/logs"


# 按照日期命名新的日志, 直接mv
cd $NGINX_LOG_PATH
one_days_ago=`date -d "1 day ago" "+%Y-%m-%d"`
tow_days_ago=`date -d "2 day ago" "+%Y-%m-%d"`
new_access_log="access.""$one_days_ago"".log"
new_error_log="error.""$one_days_ago"".log"

mv access.log "$new_access_log"
mv error.log "$new_error_log"
#向nginx主进程发送USR1信号,重新打开日志文件,否则会继续往mv后的文件写数据的。原因在于:linux系统中,内核是根据文件描述符来找文件的。如果不这样操作导致日志切割失败。
kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`

# 安装cpulimit
yum install cpulimit -y
# 安装7z压缩程序
yum install p7zip-plugins -y

# 压缩 昨天的访问日志

tow_days_ago_access_log="access."$tow_days_ago".log"
if [ -f "$tow_days_ago_access_log" ];then
    7z a "$tow_days_ago_access_log"".7z" "$tow_days_ago_access_log" &
    # $! 表示上一个后台进程的进程id, 由于压缩大文件cpu消耗大,限制cpu使用率不高于50%
    pid=`pstree -p  $!  | head -n 1 | sed 's/(/ /g' | sed 's/)/ /g'| awk '{print $4}'`
    if [ "$pid" == "" ]
    then
        echo "not process id to limit"
    else
        echo "$pid"
        cpulimit -p "$pid" -l50
        rm "$tow_days_ago_access_log"
    fi
fi

# 压缩 昨天的错误日志
tow_days_ago_error_log="error."$tow_days_ago".log"
if [ -f "$tow_days_ago_error_log" ];then
    7z a "$tow_days_ago_error_log"".7z" "$tow_days_ago_error_log" &
    pid=`pstree -p  $!  | head -n 1 | sed 's/(/ /g' | sed 's/)/ /g'| awk '{print $4}'`
    if [ "$pid" == "" ]
    then
        echo "not process id to limit"
    else
        echo "$pid"
        cpulimit -p "$pid" -l50
        rm "$tow_days_ago_error_log"
    fi
fi

# 删除过期的日志,超过7天的日志
ls -t access*.log | tail -n +8 | xargs -i rm {} -f
ls -t error*.log | tail -n +8 | xargs -i rm {} -f

echo "done `date`"

猜你喜欢

转载自blog.csdn.net/hknaruto/article/details/86368675
今日推荐