BASH

Simple Log File Monitor for Keywords with Notification

Set up a bash script to continuously monitor log files for critical keywords like 'error' or 'failed'. Get instant console notifications when a match is found, improving debugging workflows.

#!/bin/bash

# Configuration
LOG_FILE="/var/log/nginx/access.log"
KEYWORDS=("error" "failed" "critical") # Keywords to look for

# Function to check for keywords
check_log() {
  tail -n 100 "$LOG_FILE" | grep -E "$(IFS='|'; echo "${KEYWORDS[*]}")" | while read -r line;
  do
    echo "[ALERT] Found keyword in log: $line"
    # Optional: Add notification command here (e.g., sendmail, curl to Slack webhook)
    # echo "$line" | mail -s "Log Alert" [email protected]
  done
}


echo "Monitoring log file: $LOG_FILE for keywords: ${KEYWORDS[*]} (Press Ctrl+C to stop)"

# Loop indefinitely, checking every few seconds
while true;
do
  check_log
  sleep 5 # Check every 5 seconds
done
How it works: This script continuously monitors a specified log file for the occurrence of predefined keywords. It uses `tail` to check the latest entries and `grep` with extended regex to find matches. When a keyword is found, it prints an alert to the console. This snippet is invaluable for real-time debugging and quickly identifying issues in application or web server logs, with options to extend it for email or webhook notifications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs