如何使用 tail 实用程序查看频繁重新创建的日志文件
我需要一个解决方案来创建脚本来跟踪日志文件,该日志文件在达到一定大小后重新创建(具有相同的名称)。
使用“tail -f
”会导致在重新创建/旋转文件时停止拖尾。
我想做的是创建一个脚本,该脚本将跟踪文件,例如在文件达到 100 行后,然后重新启动命令...或者更好的是在重新创建文件时重新启动命令?
是否可以?
I need a solution in creating a script to tail a log file that is recreated (with the same name) after it reaches a certain 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的!使用此选项(当文件不存在或无法访问时,重试将进行尾部重试,而不仅仅是失败 - 例如可能在更改文件时):
或
或
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):
OR
OR
如果 tail -F 不可用,并且您正在尝试从 logrotate 恢复,则可以将
copytruncate
选项添加到您的logrotate .d/
规范文件,因此不是每次轮换后都创建一个新文件,而是保留并截断该文件,同时轮换出一个副本。这样,旧文件句柄将继续指向附加了新日志的新
(截断)
日志文件。请注意,在此
复制截断
过程中可能会丢失一些数据。If tail -F is not available, and you are trying to recover from logrotate, you may add the
copytruncate
option to yourlogrotate.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.尝试跑步
try running
由于您没有支持所有功能的尾部,并且没有手表,因此您可以使用无限循环的简单脚本来执行尾部。
您可能想使用 trap 来干净地退出此脚本。这取决于你。
基本上,此脚本检查 inode 编号(使用 stat -c %i "$1")是否发生变化,以终止
tail
命令并在重新创建文件时启动一个新命令。注意:您可能会删除
echo“restarting tail”
,这会污染您的输出。它仅对测试有用。如果在检查 inode 编号之后、启动 tail 进程之前替换文件,也可能会出现问题。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.
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 thetail
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.