Linux 如果关键字触发然后执行命令,Shellscript 监视日志文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4331309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:56:38  来源:igfitidea点击:

Shellscript to monitor a log file if keyword triggers then execute a command?

linuxlogfilesshell

提问by est

Is there a cheap way to monitor a log file like tail -f log.txt, then if something like [error]appears, execute a command?

有没有一种廉价的方法来监视像 那样的日志文件tail -f log.txt,然后如果[error]出现类似的东西,请执行命令?

Thank you.

谢谢你。

采纳答案by Wesley Rice

tail -fn0 logfile | \
while read line ; do
        echo "$line" | grep "pattern"
        if [ $? = 0 ]
        then
                ... do something ...
        fi
done

回答by user420783

I also found that you can use awk to monitor for pattern and perform some action when pattern is found:

我还发现您可以使用 awk 来监视模式并在发现模式时执行一些操作:

tail -fn0 logfile | awk '/pattern/ { print | "command" }'

This will execute command when pattern is found in the log. Command can be any unix command including shell scripts or anything else.

当在日志中找到模式时,这将执行命令。命令可以是任何 unix 命令,包括 shell 脚本或其他任何东西。

回答by Ari Maniatis

An even more robust approach is monit. This tool can monitor very many things, but one of them is that it will easily tail one or more logs, match against regex and then trigger a script. This is particularly useful if you have a collection of log files to watch or more than one event to trigger.

更强大的方法是monit。这个工具可以监控很多事情,但其中之一是它会很容易地跟踪一个或多个日志,匹配正则表达式,然后触发脚本。如果您要监视一组日志文件或要触发多个事件,这将特别有用。

回答by NicelyCompiled

Simple Automated Solution that covers a lot of scenarios:

简单的自动化解决方案,涵盖了很多场景:

USAGE:

用法:

logrobot localhost [default-dir],fixer,[exit-codes],[command/script-to-run-per-exit-code] [feature] [logfile] [age] [str-1] [str-2] [WARN] [CRIT] [tag] [option]

EXAMPLE:

例子:

logrobot  localhost  /tmp/logXray,fixer,0y-1y-2y,0-uname,1-who,2-uptime  autonda  /var/log/kern.log  60m  'error'  '.'  1  2  app_err_monitor  -ndshow

With this tool, you can monitor specific patterns in a log file and then trigger a command or script when the patterns are found...or NOT Found!

使用此工具,您可以监视日志文件中的特定模式,然后在找到模式时触发命令或脚本...或未找到!

The scripts or commands can be set to run based on thresholds and exit codes.

可以将脚本或命令设置为基于阈值和退出代码运行。

Tool can be downloaded directly here.

工具可以在这里直接下载。

回答by Changbin Du

Better and simple:

更好更简单:

tail -f log.txt | egrep -m 1 "error"
echo "Found error, do sth."
...