sh脚本扫描k8s一批微服务过滤错误日志生成文件,并用vim一次性打开所有日志文件进行错误排查
#!/bin/bash
echo "请输入param参数(多个参数用逗号分隔,默认为admin-center,space,permission,user,project,project-center):"
read param
param=${param:-"admin-center,space,permission,user,project,project-center"}
IFS=',' read -ra params <<< "$param" # 将参数分割成数组
line="5000" # 默认的行数5000
env="develop"
grepParam="Exception:|ERROR "
# 使用getopts解析选项参数
while getopts "e:" opt; do
case $opt in
e)
grepParam="$OPTARG"
;;
\?)
echo "无效的选项: -$OPTARG" >&2
exit 1
;;
esac
done
# 移除选项参数
shift $((OPTIND-1))
if [ -n "$1" ]; then
env=$1
fi
echo "环境为: $env"
if [ -n "$2" ]; then
line=$2
fi
echo "行数为倒数$line行"
if [ -n "$3" ]; then
grepParam=$3
fi
echo "过滤参数:$grepParam"
rm -rf *.log
for p in "${params[@]}"; do
(
echo "扫描${p}-$line行"
logs=$(kubectl logs --tail $line $(kubectl get pods -n $env | grep $p | grep -v "${p}-center" | grep -v "web2-${p}" | grep -v "web-${p}" | grep -v workspace | awk 'NR==1 {print $1}') -n $env -c $p | grep -B 5 -A 10 -E "${grepParam}")
if [[ -n $logs ]]; then
echo "$logs" > "${p}_$(date +'%Y%m%d').log"
echo "${p}有错误日志:${p}_$(date +'%Y%m%d').log"
else
echo "${p}扫描完成"
fi
) &
done
wait
echo "扫描结束"
# 查找以.log结尾的文件
files=$(find . -type f -name "*.log")
if [ -z "$files" ]; then
echo "没有错误日志"
else
vim -c "ls" $files
fi
假设保存成文件名grep.sh
,则执行.grep.sh dev 5000 -e "扫描字符串"
,第一个参数代表环境,第二个扫描行数,第三个-e可以单独使用,表示过滤的字符串,都有默认值,环境默认develop 扫描行数默认5000,-e默认Exception:
或ERROR