BASH
Monitor Web Server Logs for Errors
Continuously monitor web server log files in real-time for specific error messages or keywords, enabling immediate detection of critical issues.
#!/bin/bash
# Configuration
LOG_FILE="/var/log/nginx/error.log" # Path to your web server error log
KEYWORD="error|fail|critical|denied" # Keywords to search for (case-insensitive)
MONITOR_INTERVAL=5 # Seconds to sleep between checks
echo "Monitoring log file: ${LOG_FILE} for keywords: '${KEYWORD}'..."
echo "Press Ctrl+C to stop."
tail -F "${LOG_FILE}" | grep -Ei --line-buffered "${KEYWORD}" &
# Store the grep process ID
GREP_PID=$!
# Trap Ctrl+C to kill the background grep process
trap "echo 'Stopping log monitoring.'; kill ${GREP_PID}; exit" INT TERM
# Keep the script running (grep is in background)
wait
How it works: This script continuously monitors a specified web server log file (e.g., Nginx error log) for predefined keywords like "error" or "fail". It uses `tail -F` to follow the file for new entries and `grep -Ei --line-buffered` to filter for case-insensitive matches, displaying them in real-time. It also handles graceful exit on Ctrl+C.