BASH
Monitor Web Server Logs for Specific Errors
A bash script to continuously monitor web server error logs for specific keywords (e.g., 'error', 'failed') and alert the user, useful for real-time issue detection in web applications.
#!/bin/bash
LOG_FILE="/var/log/nginx/error.log"
KEYWORD="[crit]" # Example: "error", "failed", "FATAL"
echo "Monitoring $LOG_FILE for '$KEYWORD' errors. Press Ctrl+C to stop."
# Use tail -f to follow new entries, and a while loop with grep to filter
tail -f "$LOG_FILE" | while IFS= read -r line; do
if echo "$line" | grep -q "$KEYWORD"; then
echo "$(date): ERROR DETECTED: $line"
# Optional: Add notification logic here, e.g., send email or Slack message
# Example: send_slack_notification "ERROR in $LOG_FILE: $line"
fi
done
How it works: This script continuously monitors a specified web server error log file (e.g., Nginx, Apache) for occurrences of a defined keyword. It uses `tail -f` to follow new entries in real-time and pipes them to a `while read` loop. Inside the loop, `grep -q` efficiently checks each new line for the target keyword, printing an alert if found. This is invaluable for proactive error detection and incident response in live web applications by catching critical issues as they occur.