Servidores

tail -f frente a tail -F con rotación de logs: qué líneas se pierden, qué avisa tail y por qué grep retrasa las líneas, medido con tail 9.4

Publicado el 3 de diciembre de 2026Última revisión: 3 de diciembre de 202613 min de lectura

Resultado de la prueba

con el log renombrado (mv), `tail -f` siguió el fichero renombrado (L1, L2 y L4 escritos por el proceso que lo tenía abierto) y no mostró nada del fichero nuevo; `tail -F` y `--follow=name --retry` mostraron L1 y el fichero nuevo (L3) y perdieron lo que el proceso siguió escribiendo en el renombrado, con `'log' has become inaccessible` y `'log' has appeared; following new file` por stderr. Borrando y recreando, `tail -f` mostró solo L1 y `tail -F` los 3 (L1, L2-new y L3-new) (`has been replaced` si fue inmediato). Truncando en el sitio, los tres mostraron las 4 líneas con `file truncated`. Si el fichero se truncó y se rellenó con más contenido antes de que tail mirase, ninguno avisó y se perdió la primera línea nueva y parte de la segunda (`g-line`). Con `tail -F | grep` en tubería, sin `--line-buffered` 5 líneas escritas cada 0,2 s llegaron con 1,2 a 2,0 s de retraso (al cerrar tail) y con la opción en 0,2 s; con 100 líneas (4067 de 5000 bytes) llegaron 83 a 1 s. Mismos resultados en 3 de 3 ejecuciones, con `-s 0.2`. No se probó con inotify desactivado a propósito, ni con logrotate real, ni con BSD tail o busybox.

Contenido

Este artículo no contiene enlaces de afiliado.

Seguir un log con tail -f funciona hasta que alguien lo rota. Aquí se mide, en un directorio temporal, qué hace cada variante (-f, -F y --follow=name --retry) cuando el log se rota por renombrado, por truncado o borrándolo y recreándolo, qué líneas se ven, cuáles se pierden y qué escribe tail por stderr. Al final se mide cuánto retrasa grep sin --line-buffered una línea que llega desde tail -F por una tubería. Cómo se comporta el proceso que escribe el log con copytruncate, con renombrado y con postrotate está en logrotate con un proceso que mantiene el log abierto: copytruncate, rename y postrotate; aquí no se repite.

Condiciones: Ubuntu 24.04.5 LTS, Linux 7.0.0-1017-oracle aarch64, GNU coreutils tail 9.4, sistema de ficheros overlay, usuario sin privilegios. Todo ocurre en un directorio de mktemp -d bajo /tmp que el script borra al terminar. Las escrituras son secuenciales con pausas de 0,8 s, y tail se lanzó siempre con -s 0.2 y -n 0 (solo líneas nuevas): en una prueba previa con el intervalo por defecto (1 s) y pausas más cortas tail no llegó a notar los cambios dentro de la pausa, así que las pausas y el intervalo están ajustados para que lo haga. Con otros intervalos, el momento en que tail se entera cambia. Las escrituras "de proceso con el fichero abierto" son un descriptor del propio script (exec 3>>log), no una aplicación real. No se probó logrotate real, ni un escritor concurrente de alto ritmo, ni rotaciones con compresión, ni tail con varios ficheros, ni --pid, ni -s por defecto, ni forzar el modo sin inotify, ni BSD tail ni busybox, ni sistemas de ficheros de red. El script se ejecutó 3 veces (las tres a la vez, cada una en su directorio) y la salida fue idéntica byte a byte, también los retrasos de [8]. El texto lo redacté con ayuda de una IA a partir de la salida del script, y las cifras salen de esas ejecuciones.

Salida de la ejecución 1

Idéntica en las ejecuciones 2 y 3.

tail (GNU coreutils) 9.4
kernel: Linux 7.0.0-1017-oracle
[1] rename (mv log log.1) with the writer holding the file open (fd 3), new file written by name:
  tail -f:
    stdout: L1 L2-to-old-fd L4-old-fd
    stderr: 
  tail -F:
    stdout: L1 L3-new-file
    stderr: tail: 'log' has become inaccessible: No such file or directory|tail: 'log' has appeared;  following new file
  tail --follow=name --retry:
    stdout: L1 L3-new-file
    stderr: tail: 'log' has become inaccessible: No such file or directory|tail: 'log' has appeared;  following new file
    (on disk: log.1=L1 L2-to-old-fd L4-old-fd | log=L3-new-file)
[2] truncation in place (: > log), lines written after:
  tail -f:
    stdout: L1-aaaa L2-bbbb L3 L4
    stderr: tail: log: file truncated
  tail -F:
    stdout: L1-aaaa L2-bbbb L3 L4
    stderr: tail: log: file truncated
  tail --follow=name --retry:
    stdout: L1-aaaa L2-bbbb L3 L4
    stderr: tail: log: file truncated
[3] truncation and refill with longer content right away (A1 A2 then B1..B6):
  tail -f:
    stdout: A1 A2 g-line B2-long-line B3-long-line B4-long-line B5-long-line B6-long-line
    stderr: 
  tail -F:
    stdout: A1 A2 g-line B2-long-line B3-long-line B4-long-line B5-long-line B6-long-line
    stderr: 
  tail --follow=name --retry:
    stdout: A1 A2 g-line B2-long-line B3-long-line B4-long-line B5-long-line B6-long-line
    stderr: 
[4] rm log, 0.8 s gap, recreate by name:
  tail -f:
    stdout: L1
    stderr: 
  tail -F:
    stdout: L1 L2-new L3-new
    stderr: tail: 'log' has become inaccessible: No such file or directory|tail: 'log' has appeared;  following new file
  tail --follow=name --retry:
    stdout: L1 L2-new L3-new
    stderr: tail: 'log' has become inaccessible: No such file or directory|tail: 'log' has appeared;  following new file
[5] rm log and recreate at once:
  tail -f:
    stdout: L1
    stderr: 
  tail -F:
    stdout: L1 L2-new L3-new
    stderr: tail: 'log' has been replaced;  following new file
  tail --follow=name --retry:
    stdout: L1 L2-new L3-new
    stderr: tail: 'log' has been replaced;  following new file
[6] mv log log.1 and a new empty log at once (logrotate create style); then a line to log.1:
  tail -f:
    stdout: L1 L3-old-name-log1
    stderr: 
  tail -F:
    stdout: L1 L2-new
    stderr: tail: 'log' has been replaced;  following new file
  tail --follow=name --retry:
    stdout: L1 L2-new
    stderr: tail: 'log' has been replaced;  following new file
[7] file does not exist when tail starts (0.8 s later it is created and gets one line):
  tail -f: stdout:  | stderr: tail: cannot open 'log' for reading: No such file or directory|tail: no files remaining
  tail -F: stdout: L1 | stderr: tail: cannot open 'log' for reading: No such file or directory|tail: 'log' has appeared;  following new file
  tail -f exit status below: tail: cannot open 'log' for reading: No such file or directory
  tail -f exit status below: tail: no files remaining
  exit status of tail -f on a missing file: 1
[8] grep in a pipe from tail -F: delay of 5 matching lines written every 0.2 s (tail is stopped 1 s after the last one):
  grep (default): lines received: 5; delay in s (arrival - written): 2.0 1.8 1.6 1.4 1.2 
  grep --line-buffered: lines received: 5; delay in s (arrival - written): 0.2 0.2 0.2 0.2 0.2 
[9] same, default grep, 100 matching lines of 50 bytes (5000 bytes), checked 1 s after the last write with tail still running:
  lines received: 83 of 100 (4067 bytes)
  lines received after tail ended: 100

Lo que se ve

Qué significa

Para ver un log que rota por renombrado y que el proceso reabre, tail -F es lo que se midió que funciona; con -f el terminal se queda en el fichero viejo y no avisa. Si el proceso no reabre el log, -f ve lo que escribe pero deja de ver el nombre. --follow=name --retry salió igual que -F. Con copytruncate o : > log, cualquiera sirve, pero si el fichero crece de golpe después de truncarse se pierden líneas sin aviso. Y si el resultado de tail -F va por una tubería a grep, awk o sed, hay que pedir salida por líneas (grep --line-buffered) o las líneas llegan tarde. Este artículo no cubre un escritor concurrente ni logrotate real.

Script completo

#!/bin/bash
# tail -f vs -F vs --follow=name --retry when a log is rotated by rename, truncation and delete+recreate,
# plus grep --line-buffered in a pipe from tail -F. Everything happens in a throwaway dir under mktemp -d.
# Writes are sequential (no concurrent writer), pauses are 0.8 s so tail has time to notice each change.
# Usage: test-tail-follow-rotation.sh
export LC_ALL=C.UTF-8
W=$(mktemp -d /tmp/tailrot.XXXXXX) || exit 1
case $W in /tmp/tailrot.*) ;; *) echo "bad workdir" >&2; exit 1;; esac
trap 'kill $(jobs -p) 2>/dev/null; rm -rf "$W"' EXIT
cd "$W" || exit 1
tail --version | head -1; echo "kernel: $(uname -sr)"
P=0.8   # pause between steps; tail runs with -s 0.2 (check interval) so each change is noticed well within a pause
modes=("-f" "-F" "--follow=name --retry")

# run <scenario-function> with tail started in the given mode; show stdout and stderr separately
run(){ # $1 = scenario function, $2 = tail options
  rm -f log log.1 out err; : > log
  tail -s 0.2 -n 0 $2 log >out 2>err & local tp=$!
  sleep $P
  "$1"
  sleep $P; kill $tp 2>/dev/null; wait $tp 2>/dev/null
  echo "  tail $2:"
  echo "    stdout: $(paste -sd' ' out)"
  echo "    stderr: $(sed "s#$W/##" err | paste -sd'|')"
}
# 1) rename: a process holding the file open (fd 3) writes before and after the mv; a new file is created and written by name
s_rename(){ exec 3>>log; echo L1 >&3; sleep $P; mv log log.1; sleep $P; echo L2-to-old-fd >&3
  sleep $P; echo L3-new-file >> log; sleep $P; echo L4-old-fd >&3; exec 3>&-
  echo "    (on disk: log.1=$(paste -sd' ' log.1) | log=$(paste -sd' ' log))" >> ondisk; }
# 2) truncation in place, then new lines
s_trunc(){ echo L1-aaaa >> log; echo L2-bbbb >> log; sleep $P; : > log; sleep $P; echo L3 >> log; sleep $P; echo L4 >> log; }
# 3) truncation and refill in one go, new content longer than the old one
s_trunc_fast(){ echo A1 >> log; echo A2 >> log; sleep $P; : > log; for i in 1 2 3 4 5 6; do echo "B$i-long-line" >> log; done; }
# 4) delete, wait, recreate
s_del_gap(){ echo L1 >> log; sleep $P; rm log; sleep $P; echo L2-new >> log; sleep $P; echo L3-new >> log; }
# 5) delete and recreate immediately
s_del_fast(){ echo L1 >> log; sleep $P; rm log; echo L2-new > log; sleep $P; echo L3-new >> log; }
# 6) logrotate style: mv, then a new empty file by name
s_mv_new(){ echo L1 >> log; sleep $P; mv log log.1; : > log; sleep $P; echo L2-new >> log; echo L3-old-name-log1 >> log.1; }

for sc in rename trunc trunc_fast del_gap del_fast mv_new; do
  case $sc in
    rename) t="[1] rename (mv log log.1) with the writer holding the file open (fd 3), new file written by name";;
    trunc) t="[2] truncation in place (: > log), lines written after";;
    trunc_fast) t="[3] truncation and refill with longer content right away (A1 A2 then B1..B6)";;
    del_gap) t="[4] rm log, 0.8 s gap, recreate by name";;
    del_fast) t="[5] rm log and recreate at once";;
    mv_new) t="[6] mv log log.1 and a new empty log at once (logrotate create style); then a line to log.1";;
  esac
  echo "$t:"
  rm -f ondisk
  for m in "${modes[@]}"; do run s_$sc "$m"; done
  [ -f ondisk ] && tail -n 1 ondisk
done

echo "[7] file does not exist when tail starts (0.8 s later it is created and gets one line):"
for m in "-f" "-F"; do
  rm -f log out err; tail -s 0.2 -n 0 $m log >out 2>err & tp=$!
  sleep $P; echo L1 >> log; sleep $P; kill $tp 2>/dev/null; wait $tp 2>/dev/null; rc=$?
  echo "  tail $m: stdout: $(paste -sd' ' out) | stderr: $(sed "s#$W/##" err | paste -sd'|')"
done
rm -f log out err; tail -f log 2>&1 | sed 's/^/  tail -f exit status below: /'; echo "  exit status of tail -f on a missing file: ${PIPESTATUS[0]}"

echo "[8] grep in a pipe from tail -F: delay of 5 matching lines written every 0.2 s (tail is stopped 1 s after the last one):"
# tail writes into a fifo that grep reads, so the pid of tail is known and only that process is signalled
for gopt in "" "--line-buffered"; do
  rm -f log recv fifo; : > log; mkfifo fifo
  tail -s 0.2 -n 0 -F log > fifo & tp=$!
  ( grep $gopt MATCH < fifo | while read -r l; do echo "$(date +%s.%N) $l" >> recv; done ) & pp=$!
  sleep $P
  for i in 1 2 3 4 5; do echo "MATCH $i $(date +%s.%N)" >> log; sleep 0.2; done
  sleep 1; kill $tp; wait $tp 2>/dev/null; wait $pp 2>/dev/null
  echo "  grep ${gopt:-(default)}: lines received: $(wc -l < recv); delay in s (arrival - written): $(awk '{printf "%.1f ", $1-$4}' recv)"
done
echo "[9] same, default grep, 100 matching lines of 50 bytes (5000 bytes), checked 1 s after the last write with tail still running:"
rm -f log recv fifo; : > log; mkfifo fifo
tail -s 0.2 -n 0 -F log > fifo & tp=$!
( grep MATCH < fifo | while read -r l; do echo "$l" >> recv; done ) & pp=$!
sleep $P
for i in $(seq 1 100); do printf 'MATCH %03d xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n' $i >> log; done
sleep 1; echo "  lines received: $(wc -l < recv 2>/dev/null || echo 0) of 100 ($(wc -c < recv 2>/dev/null || echo 0) bytes)"
kill $tp; wait $tp 2>/dev/null; wait $pp 2>/dev/null
echo "  lines received after tail ended: $(wc -l < recv)"

Este artículo no contiene enlaces de afiliado.