BASH
Real-time Log File Monitoring for Keywords
Monitor a specified log file continuously for the occurrence of specific keywords, useful for real-time debugging and error detection in web server logs.
#!/bin/bash
monitor_log_for_keywords() {
if [ -z "$1" ] || [ -z "$2" ]; then
echo "Usage: monitor_log_for_keywords <log_file_path> <keyword1> [keyword2 ...]"
return 1
fi
LOG_FILE="$1"
shift
KEYWORDS=($@)
if [ ! -f "$LOG_FILE" ]; then
echo "Error: Log file '$LOG_FILE' not found."
return 1
fi
echo "Monitoring '$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 '$keyword': $line"
fi
done
done
}
# To use:
# monitor_log_for_keywords /var/log/nginx/access.log error warn failed
How it works: This script provides a real-time log monitoring solution. It uses `tail -F` to continuously output new lines from a specified log file. Each new line is then checked against a list of user-defined keywords. If any keyword is found, the script prints a timestamped alert along with the matching log line. This is invaluable for quickly spotting errors, warnings, or specific events in web server or application logs.