问题描述
我想监视一个日志文件,当新的日志消息与我定义的模式匹配(例如包含错误")时,然后向我发送电子邮件.
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.
为此,我编写了一个python脚本monitor.py,主要部分如下:
To do that, I wrote a python script monitor.py, the main part looks like:
import sys
for line in sys.stdin:
if "error" in line:
print line
当我使用tail my.log | python monitor.py
时效果很好,然后我切换到tail -f my.log | python monitor.py
,则它不起作用,至少不是立即生效.
It works well when I use tail my.log | python monitor.py
, then I switch to tail -f my.log | python monitor.py
, then it doesn’t work, at least not immediately.
我已经做过一些测试,当日志中的新内容累积到8KB时,我的python脚本可以从tail中获取输出.因此,我高度怀疑这是由stdin/stdout缓冲区大小控制的.如何立即获得输出?
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. So I highly suspect that this is controlled by the stdin/stdout buffer size. How can I get the output immediately?
还有一个问题,当我使用tail -f my.log
和tail -f my.log | grep error
时,为什么它可以立即显示输出?
One more question, when I use tail -f my.log
and tail -f my.log | grep error
, why it could show me the output immediately?
推荐答案
如果stdout连接到TTY,则大多数Linux程序将使用行缓冲,否则将使用全缓冲.您可以使用 stdbuf
强制行缓冲.
Most Linux programs will use line buffering if stdout is connecting to a TTY and full buffering otherwise. You can use stdbuf
to force line buffering.
stdbuf -oL tail -f my.log | python monitor.py
这篇关于如何获得“即时"的将"tail -f"的输出作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!