Tail Follow Streaming Log Filter

Stream growing log files with tail -F and grep pipelines, highlighting patterns and stopping cleanly on signals.

BashCli Tooling

Code

bashsnippet
38 lines
#!/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 "日志流已停止"

How the snippet works

set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.

The work is delegated to readonly, trap, tail, stream_logs and sleep, chained through 12 pipes so each stage’s output feeds the next.

2 helper functions (on_term and stream_logs) keep the repeated logic out of the main flow.

The script leans on parameter expansion 10 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.

A trap handles termination signals so temporary state is cleaned up even on early exit.

What to watch for

  • The pipeline is 12 stages deep — when it misbehaves, split the pipe and test the stages separately.

Statements that decide the outcome

readonly PATTERNS='ERROR|WARN|Traceback'
tail -F --lines=50 "${LOG_FILE}" 2>/dev/null \
  | grep --line-buffered -E "${PATTERNS}" \
  | while IFS= read -r line; do
      case "$line" in
while $running; do
  sleep 1

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`readonly`, `trap`, `tail`, `stream_logs`, `sleep` must be available on the PATH environment variable; everything else is shell built-in syntax.