linux 日志回滚、切割、压缩脚本

#!/bin/sh              
                      
LOGPATH="/var/log/app/"
LOGPATHBAK="/userapp/log/"

APPS="RecordServer PlatformAccess"

USERAPP_LOGS="syslog usrlog"

LOGSIZE_MAX=$((512*1024))

if [ ! -e ${LOGPATH} ]
then
	echo '###make dir for log'
	mkdir -p ${LOGPATH}
fi

if [ ! -e ${LOGPATHBAK} ]
then
	echo '###make dir for bak log'
	mkdir -p ${LOGPATHBAK}
fi

#LogIdx=$(($(find ${LOGPATHBAK} -name "${processname}*" | awk -F "_" '{print $2}' | awk -F "." '{print $1}' | awk 'BEGIN {max = 0; while(getline) max = (max > $0) ? max : $0;{print max}}')))
while [ 1 ]            
do         
		#检测userapp/log/中app应用日志
		for processname in ${APPS}
		do                                                                 
			ppfirst=`ps |  grep ${processname} | grep -v grep | awk 'END{print NR}'`
			if [ "${ppfirst}" = "0" ]                                                
			then                                                      
				echo "The ${processname} is no running"
				sleep 1                                
				ppsecond=`ps |  grep ${processname} | grep -v grep | awk 'END{print NR}'`
				if [ "${ppsecond}" = "0" ]                                                    
				then                     
					tail -n 300 ${LOGPATH}${processname}.log > ${LOGPATHBAK}x${processname}.log                   
				fi                                                          
			fi        
			  
			if [ -e "${LOGPATH}${processname}.log" ]
			then                                    
				APPLOGSIZE=`ls -l ${LOGPATH}${processname}.log | awk '{print $5}'`
				echo "${processname}.log size is ${APPLOGSIZE},maxsize is ${LOGSIZE_MAX}"
				if [ ${APPLOGSIZE} -gt ${LOGSIZE_MAX} ] 
				then  
					if [ -e "${LOGPATHBAK}${processname}.idx" ];then
						LogIdx=$(($(cat ${LOGPATHBAK}${processname}.idx)))
					else
						LogIdx=0
					fi
					echo "${processname}.log is over"
					LogIdx=$(($LogIdx+1))
					echo "logIdx is ${LogIdx}"
					if [ $LogIdx -gt 10 ];then
						LogIdx=0
					fi
					gzip -k ${LOGPATH}${processname}.log
					mv ${LOGPATH}${processname}.log.gz ${LOGPATHBAK}${processname}"_$LogIdx".log.gz 
					echo "delete ${processname}.log , ${APPLOGSIZE} > ${LOGSIZE_MAX}"      
					echo $LogIdx > ${LOGPATHBAK}${processname}.idx
					echo "" > ${LOGPATH}${processname}.log
				fi 
			else
				touch ${LOGPATH}${processname}.log
			fi
			
			sleep 1
		done    
		sleep 3
done           

你可能感兴趣的:(Linux,linux,服务器,运维)