Tail Follow Streaming Log Filter
Stream growing log files with tail -F and grep pipelines, highlighting patterns and stopping cleanly on signals.
Code
#!/usr/bin/env bash
set -euo pipefail
readonly LOG_FILE="${1:-/var/log/app/application.log}"
readonly PATTERNS='ERROR|WARN|Traceback'
running=true
on_term() { running=false; }
trap on_term INT TERM
stream_logs() {
# -F 处理轮转:文件被重建后继续跟随
tail -F --lines=50 "${LOG_FILE}" 2>/dev/null \
| grep --line-buffered -E "${PATTERNS}" \
| while IFS= read -r line; do
case "$line" in
*ERROR*) printf '\033[31m%s\033[0m\n' "$line" ;;
*WARN*) printf '\033[33m%s\033[0m\n' "$line" ;;
*Traceback*) printf '\033[35m%s\033[0m\n' "$line" ;;
esac
done
}
[[ -f "${LOG_FILE}" ]] || { echo "日志文件不存在: ${LOG_FILE}" >&2; exit 1; }
echo "跟随 ${LOG_FILE} 中的 ${PATTERNS},Ctrl-C 退出"
stream_logs &
readonly TAIL_PID=$!
while $running; do
sleep 1
kill -0 "${TAIL_PID}" 2>/dev/null || running=false
done
kill "${TAIL_PID}" 2>/dev/null || true
wait "${TAIL_PID}" 2>/dev/null || true
echo "日志流已停止"
Report a problem with this exampleOpens a pre-filled issue on GitHub.