Shellscript to monitor a log file if keyword trigg

2019-01-16 06:44发布

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

Thank you.

5条回答
三岁会撩人
2楼-- · 2019-01-16 07:10
tail -fn0 logfile | \
while read line ; do
        echo "$line" | grep "pattern"
        if [ $? = 0 ]
        then
                ... do something ...
        fi
done
查看更多
爷的心禁止访问
3楼-- · 2019-01-16 07:13

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

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-16 07:17

Batter and simple:

tail -f log.txt | egrep -m 1 "error"
echo "Found error, do sth."
...
查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-16 07:26

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.

查看更多
Juvenile、少年°
6楼-- · 2019-01-16 07:28

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.

查看更多
登录 后发表回答