Score:0

Script to scan log file

kr flag

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.

cn flag
`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`?
user240614 avatar
kr flag
@NasirRiley yes, there is a script to generate the output every 1 minutes via cron.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.