BASH
Dynamic Log File Tail with Filtering
A bash script to continuously monitor (tail) a log file, optionally filtering its output based on a keyword, useful for debugging web applications.
#!/bin/bash
# Dynamic Log File Tail with Filtering
LOG_FILE="$1"
FILTER_KEYWORD="$2"
if [ -z "$LOG_FILE" ]; then
echo "Usage: $0 <log_file_path> [filter_keyword]"
echo "Example: $0 /var/log/nginx/access.log"
echo "Example: $0 /var/log/nginx/error.log \"failed login\""
exit 1
fi
if [ ! -f "$LOG_FILE" ]; then
echo "Error: Log file not found at $LOG_FILE"
exit 1
fi
echo "Tailing log file: $LOG_FILE"
if [ -n "$FILTER_KEYWORD" ]; then
echo "Filtering by keyword: '$FILTER_KEYWORD'"
tail -f "$LOG_FILE" | grep --line-buffered "$FILTER_KEYWORD"
else
echo "No filter keyword provided. Showing all lines."
tail -f "$LOG_FILE"
fi
# Add a trap to ensure graceful exit on Ctrl+C
trap "echo -e '
Exiting log tail.'; exit 0" SIGINT SIGTERM
How it works: This script continuously tails (monitors) a specified log file, displaying new lines as they are added. Optionally, it can accept a `FILTER_KEYWORD` argument to only show lines containing that keyword. This dynamic filtering makes it significantly easier to pinpoint specific events, errors, or user activities in busy web application log files, greatly aiding the debugging process.