LINUXSHELL抓取错误日志脚本


背景

任何程序运行起来免不了产生很多日志,其中错误日志需要最为关心的。在某些时候会将错误日志和正常日志分开,但我们的系统却没有这么做。更麻烦的是,每个小时存储一个日志文件,所以每次为了查找当天是否有错误信息需要打开N个文件,而且不能用grep因为需要把整个堆栈抓取下来。

SHELL

本人对shell完全是初学,磕磕碰碰写了个脚本。主要逻辑是判断ERROR的日志级别的那一行开始记录,直到碰到下一个INFO或者DEBUG的日志级别行。
#!/bin/bash

isInErrorBlock=false

strArray=()
count=1


while read line

do

  #echo "Line $count:"

  arrayIdx=$count%10
   strArray[$count]="$line"
  

   idx=$(expr match "${strArray[$count]}" ".*ERROR")

   if [ $idx -le 0 ];
   then
	idx=$(expr match "${strArray[$count]}" ".*Exception*")
   fi

	
   idx2=$(expr match "${strArray[$count]}" ".*DEBUG")
   idx3=$(expr match "${strArray[$count]}" ".*INFO")


   if [ $idx -gt 0 ] ;
   then
	if ! $isInErrorBlock;
	then		
		echo 'print out previous lines'
		isInErrorBlock=true
		echo ${strArray[$count]}

	fi
   else
	if [ $idx2 -gt 0 ] || [ $idx3 -gt 0 ] ;
		
	then
		isInErrorBlock=false
	else
		if $isInErrorBlock;
		then
		echo ${strArray[$count]} 
		fi

	fi
   fi
   count=$[ $count+1 ]
done

#echo "finish\n"

exit 0

效果

基本达到了要求,对于每个目录 cat *log | sh find_error.sh 能够将整个堆栈单独输出到一个文件。但是效率很慢,不知道如何才能提高SHELL的运行效率。

相关内容