开发者

How can I use tail utility to view a log file that is frequently recreated

I need a solution in creating a script to tail a log file that is recreated (with the same name) after it reaches a cert开发者_StackOverflow社区ain size.

Using "tail -f" causes the tailing to stop when the file is recreated/rotated.

What I would like to do is create a script that would tail the file and after it reaches 100 lines for example, then restart the command... Or even better to restart the command when the file is recreated?

Is it possible?


Yes! Use this (the retry will make tail retry when the file doesn't exist or is otherwise inaccessible rather than just failing - such as potentially when you are changing files):

tail -f --retry <filename>

OR

tail --follow=name --retry

OR

tail -F <filename>


try running

watch "tail -f" yourfile.log


If tail -F is not available, and you are trying to recover from logrotate, you may add the copytruncate option to your logrotate.d/ spec file so instead of creating a new file each time after rotation, the file is kept and truncated, while a copy is rotated out.

This way the old file handle continues to point to the new (truncated) log file where new logs are appended.

Note that there may be some loss of data during this copy-truncate process.


Since you dont have a tail that support all the features and because you dont have watch you could use a simple script that loop indefinitely to execute the tail.

#!/bin/bash 

PID=`mktemp`
while true;
do
  [ -e "$1" ] && IO=`stat -c %i "$1"`
  [ -e "$1" ] && echo "restarting tail" && { tail -f "$1" 2> /dev/null & echo $! > $PID; }

  # as long as the file exists and the inode number did not change
  while [[ -e "$1" ]] && [[ $IO = `stat -c %i "$1"` ]]
  do
     sleep 0.5
  done
  [ ! -z $PID ] && kill `cat $PID` 2> /dev/null && echo > $PID
  sleep 0.5
done 2> /dev/null
rm -rf $PID

You might want to use trap to cleanly exit this script. This is up to you.

Basicaly, this script check if the inode number (using stat -c %i "$1") change to kill the tail command and start a new one when the file is recreated.

Note: you might get rid of the echo "restarting tail" which will pollute your output. It was only useful for testing. Also problems might occur if the file is replaced after we check the inode number and before we start the tail process.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜