shell脚本查询所有的error日志

#!/bin/sh

select_dir=$1
input_time=$2
# 获取需要查询的时间
if [[ "${input_time}" =~ 'd' ]]; then
    se_time="$(echo "${input_time}" | grep -Po "[0-9]+") days"
elif [[ "${input_time}" =~ 'h' ]]; then
    se_time="$(echo "${input_time}" | grep -Po "[0-9]+") hours"
elif [[ "${input_time}" =~ 'm' ]]; then
    se_time="$(echo "${input_time}" | grep -Po "[0-9]+") minutes"
fi
# 每次查询前清空error.log
sed -i '1,$d' error.log
declare -a all_time
time_format='[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}'
now_date=`date "+%Y-%m-%d %H:%M:%S"`
find_date=`date -d "${se_time} ago" "+%Y-%m-%d %H:%M:%S"`
echo "find time is ${find_date}"
# 查找出所有log文件,先找出对应具体时间段,再区分每个最小时间段,查询最小时间段中的error
for log in `find ./${select_dir} -name '*.log'`; do
    echo ${log}
    echo ${log} >> error.log
    cat ${log} | while read line; do
        time=$(echo $line | cut -d \, -f 1)
        if [[ "${time}" =~ ${time_format} ]]; then
            time=$(echo "${time}" | grep -Po "${time_format}")
        else
            continue
        fi
        if [[ "${time}" > "${find_date}" ]] && [[ "${time}" < "${now_date}" ]]; then 
            all_time+=("${time}")
            next=${all_time[${#all_time[@]}-2]}
            last=${all_time[${#all_time[@]}-1]}
            if [ "${next}" == "${last}" ]; then
                continue
            else
                data=$(sed -n "/${next}/,/${last}/p" ${log})
                if [[ ${data} =~ "ERROR" ]] || [[ ${data} =~ "Error" ]]; then
                    echo '------------'
                    echo ${time}
                    echo "${data}" >> error.log
                fi
            fi
        fi
    done
    echo ' ' >> error.log
done
echo "end"

使用格式:

sh monitor.sh <your_product> <time>

<your_product>目录是项目目录
<time>是需要查询的时间,30m表示需要查询30分钟前至当前时间的error日志,3h表示查询3小时前至当前时间的error日志

发布了23 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Misaki_root/article/details/92630954