0

I have a log file with the content below. Let's call it as cpu_usage.out:

2023-04-12 12:04: CPU STATISTICS CRITICAL : USED:- 2.52% IDLE:- 97.49%|CpuUsed=2.52;0;1 CpuIdle=97.49;0;1
2023-04-12 12:05: CPU STATISTICS WARNING : USED:- 0.5% IDLE:- 99.50%|CpuUsed=0.5;0;1 CpuIdle=99.50;0;1
2023-04-12 12:06: CPU STATISTICS CRITICAL : USED:- 3% IDLE:- 97.00%|CpuUsed=3;0;1 CpuIdle=97.00;0;1
2023-04-12 12:07: CPU STATISTICS CRITICAL : USED:- 1.53% IDLE:- 98.48%|CpuUsed=1.53;0;1 CpuIdle=98.48;0;1
2023-04-12 12:08: CPU STATISTICS CRITICAL : USED:- 4% IDLE:- 96.00%|CpuUsed=4;0;1 CpuIdle=96.00;0;1
2023-04-12 12:09: CPU STATISTICS CRITICAL : USED:- 3% IDLE:- 97.00%|CpuUsed=3;0;1 CpuIdle=97.00;0;1

This log file is generating via cron (1 min interval) to monitor CPU util. Now I need to write another script to scan this log file. I need the script:

  1. Detects "CRITICAL" keyword and hold it for 30 minutes
  2. If continuously 30 minutes, send an email and terminate the tail command
  3. Otherwise, do nothing

I have simple script below but I do not know how to monitor the "CRITICAL" keyword for about 30 mins continuously.

#!/bin/bash

tail -f /root/cpu_usage.out | while read line
do case "$line" in
    *"CRITICAL"*) echo "$line"
    #*"CRITICAL"*) echo "$line" | mutt -s "The CPU of server $(hostname) is high for about 30 minutes ago" [email protected];
    ;;
esac
done

I have tried the following script but when I ran it, the cursor just hanging there

#!/bin/bash


LOGFILE=/root/cpu_usage.out

tail -fn30 $LOGFILE | while read line;
do
CRIT=$(echo $LOGFILE | grep -m 30 "CRITICAL" | wc -l)

if [[ $CRIT -ge 30 ]]
then
  pkill -P $$ tail
  echo "$line"
fi
done

Note: forget first on email part. I will take it later.

Please advice.

2
  • tail -f sends the contents of the file to stdout as it is written to. Is there actually a process writing to the particular file /root/cpu_usage.out? Commented Apr 12, 2023 at 11:30
  • @NasirRiley yes, there is a script to generate the output every 1 minutes via cron. Commented Apr 13, 2023 at 2:07

0

You must log in to answer this question.

Browse other questions tagged .