BASH
Real-time Log Monitoring and Filtering with Bash
Effectively monitor application or server logs in real-time using Bash, with the ability to filter output for specific keywords and highlight important messages.
#!/bin/bash
# --- Configuration ---
LOG_FILE="/var/log/nginx/access.log" # Example: Nginx access log
KEYWORD="error" # Keyword to filter logs by
HIGHLIGHT_COLOR="\033[0;31m" # Red color for highlighting
RESET_COLOR="\033[0m"
# Check if log file exists
if [ ! -f "$LOG_FILE" ]; then
echo "Error: Log file '$LOG_FILE' not found."
exit 1
fi
echo "Monitoring log file: $LOG_FILE for keyword: '$KEYWORD'"
echo "Press Ctrl+C to stop."
# Tail the log file and process lines
tail -f "$LOG_FILE" | while IFS= read -r line
do
if echo "$line" | grep -q "$KEYWORD"; then
# Highlight the keyword if found
echo -e "$(echo "$line" | sed "s/\($KEYWORD\)/$HIGHLIGHT_COLOR\1$RESET_COLOR/g")"
else
# Print line normally if keyword not found (or if no filtering is desired, remove 'if' block)
echo "$line"
fi
done
How it works: This script enables real-time monitoring of a specified log file using `tail -f`. It continuously reads new lines, and if a defined `KEYWORD` is found within a line, it highlights that keyword in the terminal using ANSI escape codes for better visibility. This is highly useful for debugging and quickly spotting critical events in server or application logs.