问题
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.
回答1:
tail -fn0 logfile | \
while read line ; do
echo "$line" | grep "pattern"
if [ $? = 0 ]
then
... do something ...
fi
done
回答2:
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.
回答3:
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.
回答4:
Batter and simple:
tail -f log.txt | egrep -m 1 "error"
echo "Found error, do sth."
...
回答5:
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.
来源:https://stackoverflow.com/questions/4331309/shellscript-to-monitor-a-log-file-if-keyword-triggers-then-execute-a-command