【问题标题】:Tailing Rolling Files拖尾滚动文件
【发布时间】:2012-01-28 16:20:27
【问题描述】:

我有一个充满滚动日志文件的目录,我希望能够在这些文件上使用 tail。

文件命名如下:

name      modified
00A.txt   Dec 27 19:00
00B.txt   Dec 27 19:01
00C.txt   Dec 27 19:02
00D.txt   Dec 27 19:03

在较旧的 unix 系统上,我正在尝试编写一个 shell 脚本,该脚本将跟踪特定目录中最近修改的文件,如果该文件被管理性关闭(滚动到下一个文件),我想要程序自动开始拖尾新文件,而我不必打破尾巴重新运行。

tail -100f `ls -t | head -1` 

考虑到上述文件名,所需的行为将如下所示:

./logtailer.sh

然后脚本将开始跟踪 00D.txt。一旦记录器完成对 00D.txt 的写入并且最新的日志文件现在命名为 00E.txt,程序就会自动开始跟踪该文件。

可以通过观察 tail 的输出文本“File Administratively Closed”然后再次运行以下命令来编写此脚本。

tail -100f `ls -t | head -1`

有没有比观察文本“文件管理关闭”更优雅的方法来做到这一点?如何在 shell 脚本中逐行读取 tail 的输出?

编辑:我应该解释一下,在这个系统上,tail 的 -F 标志对我来说不是一个选项。它使用不包含此功能的不同版本的 tail。 操作系统版本 - Solaris 10

【问题讨论】:

    标签: bash shell logging tail


    【解决方案1】:

    您可以为tail 使用-F 选项,这意味着--follow=name --retry

    来自man 页面:

    -F      
    The -F option implies the -f option, but tail will also check to see if the 
    file being followed has been renamed or rotated.  The file is closed and 
    reopened when tail detects that the filename being read from has a new inode 
    number. The -F option is ignored if reading from standard input rather than 
    a file.
    

    【讨论】:

    • 我希望我可以使用这个标志,但是我的 tail 版本没有这个功能,我没有升级它的选项。 (无管理权限)
    • 能否提供tailversion info和您正在使用的box (unix/linux)
    • 您必须与您的管理员联系以安装名为 Multitail 的第三方实用程序。
    • -1,这不是 OP 所要求的。 tail --follow=name 用于当输入文件被日志轮换脚本截断,但 OP 希望在新文件出现时开始读取它。
    • 我建议tail -F 选项正是这样做的。 OP 在他的 Solaris 盒子上没有这个选项。
    【解决方案2】:

    您可能需要inotify 来检测新文件的创建,解决方法是在后台运行tail 时继续轮询文件系统:

    #!/bin/bash
    
    get_latest() {
        local files=(*.log)
        local latest=${files[${#files[@]}-1]}
        echo "$latest"
        [[ $latest == $1 ]]
    }
    run_tail() {
        tail -c +0 -f "$1"
    }
    
    while true; do
        while current=$(get_latest "$current"); do
            sleep 1
        done
        [[ $pid ]] && kill $pid
        run_tail "$current" & pid=$!
    done
    

    (未经测试,不必要的hacky,请注意旧系统的局限性!)

    【讨论】:

    • 我喜欢这个答案的去向......我无法将它直接插入到 shell 脚本中并让它做我想做的事情,但我会玩看看这里的代码,看看我能做些什么来让它工作。
    猜你喜欢
    • 2020-06-21
    • 2023-03-16
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多