centos下sh脚本监控文件内容告警

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:41   1806   0

实现功能: centos下脚本监听某个java项目下的Exception 日志,当监听到日志里出现 "Exception" 字符时进行告警

脚本启动命令: nohup sh z_jiankong1.sh >/dev/null 2>&1 &

#!/bin/bash
#--------------------------------------------
# 监听服务器日志, 如果出现错误,发微信告警
# author:by zero
# start commod: nohup sh z_jiankong1.sh >/dev/null 2>&1 &
#--------------------------------------------
sitename='我的网站1'
logfile='/home/web/log/error.log'
shelllog='/home/web/log/wxerr01.log'
beforelinenum=`sed -n '$=' $logfile`
#echo $beforelinenum
secondspan=10
t1=`date '+%Y-%m-%d %H:%M:%S'`
echo "$t1 $sitename 开始监听 $logfile, $beforelinenum" >> $shelllog
while true
do
  afterlinenum=`sed -n '$=' $logfile`
  #当日志文件清空时重置起始点,通常日志会换天写文件
  if [ $afterlinenum -lt $beforelinenum ];then
    beforelinenum=0
  fi
  line=$(( $afterlinenum - $beforelinenum ))
  #echo " line:"$line >> $shelllog
  beforelinenum=$afterlinenum
  content=`tail -n $line $logfile |grep -A 20 'Exception'`
  if [ -n "$content" ]; then
        t1=`date '+%Y-%m-%d %H:%M:%S'`
        t2=$(date +\%Y\%m\%d\%H\%M\%S)
        echo "$t1 $sitename line:$line content:$content" >> $shelllog
        echo -e "服务器发生异常,准备发送告警web" >> $shelllog
        #curl -d "msg1="$sitename"&msg2=Exception" https://www.baidu.com/notify/wxmsg
        echo "发送完成..." >> $shelllog

  fi
  sleep $secondspan
done
echo "程序退出." >> $shelllog
exit

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP