使用 bash 脚本监控 nginx 响应时间

使用 bash 脚本监控 nginx 响应时间

我需要监控 nginx 日志文件。如果响应时间大于特定值,我需要发送邮件警报。我使用了以下脚本。但在 cronjob 中执行时,会跳过一些日志行。预期结果:- 当日志中的第 15 列大于 1.000ms 时触发邮件。

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DATE=$(date +%Y-%m-%d)
DATE1=$(date +%Y-%m-%dT%H:%M:%S)
###########################################
#This section counts the number of lines appended in the logs for last 10 seconds. And the number is saved into variable "dif". By using this value, we can make avoid repetitions.
before=$(wc -l < /var/log/nginx/access.log)
sleep 10
after=$(wc -l < /var/log/nginx/access.log)
let dif=$after-$before
echo "$dif"
############################################
MS=`tail -n $dif /var/log/nginx/access.log | awk '{ print $15}' | grep -o '[0-9]\.[0-9][0-9][0-9]' | sort -V | sort -nr | head -n1`
echo $DATE1 >> /root/scripts/analysing.log
echo $MS >> /root/scripts/analysing.log
var1=`tail -n $dif /var/log/nginx/access.log | grep -B1 "$MS"|awk 'FNR == 1 {print}' | cut -d 'I' -f 3`
echo " "
echo "Last Recorded & Nginx Highest Execution Time (Millisecond) is: $MS "
echo " "
if [ 1 -eq "$(echo "${MS} > 10.000" | bc)" ]
then
echo "Current Status: Problem!!" 
echo "Description: Nginx Request Processing Time Is High!!"
echo "Nginx request execution time is greater than 10000ms on "$DATE1" I"$var1" " | mail -s "e-Agree Nginx Crossed Normal Execution Limit" -a "From: Alerts <[email protected]>" "[email protected]"
fi

答案1

找到了使用字数统计命令的解决方案。

  • 将值存储${wc -l filename}到脚本末尾的文件中
  • 上述值被放入变量中并用作起始行号
  • 并将当前${wc -l filename}值作为结束行号

通过使用这种逻辑,我避免了重复和跳过行。

并将此脚本添加到crontab中,每分钟运行一次。

相关内容