BASH
Monitor Log File for Keywords and Count Occurrences
A bash script to continuously monitor a log file, filter lines by keywords, and count their occurrences, useful for debugging and error tracking.
#!/bin/bash
LOG_FILE="/var/log/nginx/access.log"
KEYWORDS=("error" "warning" "failed")
COUNT=0
echo "Monitoring log file: $LOG_FILE for keywords: ${KEYWORDS[*]}"
tail -F "$LOG_FILE" | while read LINE; do
for KEYWORD in "${KEYWORDS[@]}"; do
if [[ "$LINE" =~ "$KEYWORD" ]]; then
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Found '$KEYWORD': $LINE"
((COUNT++))
echo "Total matches found: $COUNT"
break # Exit inner loop once keyword is found in line
fi
done
done
How it works: This script uses `tail -F` to follow a log file in real-time, displaying new lines as they are appended. It then pipes each new line to a `while read LINE` loop. Inside the loop, it iterates through a list of defined `KEYWORDS`. If a line contains any of the keywords, it prints the line with a timestamp and increments a counter. This is highly useful for real-time debugging, tracking specific events, or monitoring server health by looking for critical messages.