linux - 在 linux 上跟踪日志文件并在单词匹配时触发脚本

标签 linux logging monitor logfiles

我正在寻找一种在 Linux 上查看多个日志文件并在其中查找单词或短语的方法,如果找到,则触发脚本或操作,这需要保持不变。

我知道这可以通过一些 grep、tail hack 来完成,但我想知道是否有一些预制的配置选项,例如,我认为 logtail 可以监视文件但不能触发操作。

有什么想法吗?

最佳答案

您可以将 grep 的输出设置为一个变量,然后评估它是否为空以运行您的脚本/操作。

例子:

使用 $( whatever command ) 将命令输出转换为字符串
line=$(  grep -m 1 YourKeyWord <( exec tail -f /directory/of/log.out ); kill $! 2> /dev/null)
然后您可以开始评估每个日志,并确定以下操作。
if [ "$line"!="" ]
then
echo "Found $line"
service something start
line=""
echo "Now we can look for ABC"
fi

line=$(  grep -m 1 ABC <( exec tail -f /your/otherdir/of/log.out ); kill $! 2> /dev/null)
if [ "$linea!="" ]
then
echo "Found the other $linea"
ntpstat (or whatever command you need)
line=""
echo "And we can keep doing this"
fi

您可以使用两个函数来完成此操作(一个用于重置 $line,另一个用于执行 grep,使用 $Dir var)但是为了详细的答案,让我们离开这个方式。

这条线,

grep -m 1 WhateverWord <( exec tail -f /your/otherdir/of/log.out ); kill $! 2> /dev/null

取自答案 https://superuser.com/questions/275827/how-to-read-one-line-from-tail-f-through-a-pipeline-and-then-terminate通过以下解释,它确实避免了服务器中的逻辑问题。

"kill will kill leftover tail -f process, and we hide errors, because it's possible that the tail will be gone by the time kill will be invoked."

关于linux - 在 linux 上跟踪日志文件并在单词匹配时触发脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33579972/

相关文章:

python - 与 bsddb 有关的许可证问题

linux - DRBD 解析错误 : got 'incon-degr-cmd' (TK 282) on CentOS

c - Linux NFQUEUE 处理问题

linux - 无法通过 ssh 进入本地主机以使用 hadoop

Android系统日志文件位置

javascript - Morgan Logger with Express.js 只记录失败的请求

c++ - linux 中可执行文件的主管

Android 日志级别

车载监控系统嵌入式项目

.net - 监视器应该等待什么对象?