简体   繁体   English

如何将“tail -f”的“即时”输出作为输入?

[英]How to get “instant" output of “tail -f” as input?

I want to monitor a log file, when a new log message match my defined pattern (say contain “error”), then send out an email to me. 我想监视日志文件,当新的日志消息与我定义的模式匹配时(比如包含“错误”),然后向我发送一封电子邮件。

To do that, I wrote a python script monitor.py, the main part looks like: 为此,我编写了一个python脚本monitor.py,主要部分如下:

import sys

for line in sys.stdin:
    if "error" in line:
        print line 

It works well when I use tail my.log | python monitor.py 当我使用tail my.log | python monitor.py时,它运行良好 tail my.log | python monitor.py , then I switch to tail -f my.log | python monitor.py tail my.log | python monitor.py ,然后我切换到tail -f my.log | python monitor.py tail -f my.log | python monitor.py , then it doesn't work, at least not immediately. tail -f my.log | python monitor.py ,然后它不起作用,至少不是立即。

I have done some tests, when the new content to the log accumulate up to 8KB, then my python script can get output from tail. 我做了一些测试,当日志的新内容累积到8KB时,我的python脚本可以从尾部输出。 So I highly suspect that this is controlled by the stdin/stdout buffer size. 所以我高度怀疑这是由stdin / stdout缓冲区大小控制的。 How can I get the output immediately? 如何立即获得输出?

One more question, when I use tail -f my.log and tail -f my.log | grep error 还有一个问题,当我使用tail -f my.logtail -f my.log | grep error tail -f my.log | grep error , why it could show me the output immediately? tail -f my.log | grep error ,为什么它可以立即显示输出?

Most Linux programs will use line buffering if stdout is connecting to a TTY and full buffering otherwise. 如果stdout连接到TTY,则大多数Linux程序将使用行缓冲,否则将使用完全缓冲。 You can use stdbuf to force line buffering. 您可以使用stdbuf强制进行行缓冲。

stdbuf -oL tail -f my.log | python monitor.py

There's a patch to add unbuffered output to tail , dating from 2008. which appears to have been rejected and my own (BSD) manpage does not indicate it. 有一个补丁可以添加无缓冲输出到尾部 ,可以追溯到2008年。这似乎被拒绝了 ,我自己的(BSD)联机帮助页没有表明它。 Perhaps you could download coreutils , apply the patch, compile tail yourself and it may still work? 也许你可以下载coreutils ,应用补丁,自己编译尾巴,它仍然可以工作?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM