49

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.

4 Answers 4

70
tail -fn0 logfile | \
while read line ; do
        echo "$line" | grep "pattern"
        if [ $? = 0 ]
        then
                ... do something ...
        fi
done
4
  • 2
    oh, one more thing, the tail -fn0 logfile seems to be expire since the HTTP server log file are quickly renamed and gzip'ed. The script is still monitor the old file-descriptor I think? Is there a way to auto update file inode or something after a period of time for the tail command?
    – est
    Dec 10, 2010 at 3:35
  • 11
    Just add a --retry to the tail command, or use -F instead of -f. That should do it.
    – Zizzencs
    Dec 14, 2010 at 14:32
  • 3
    Also consider grep -q to set the return code without displaying the matching lines.
    – Adam Liss
    Jul 14, 2013 at 12:03
  • 1
    the issue with this is, that logs like catalina,out (apache) have history, so "finished in" kinda patterns already exist. is there a way only check for future logs ?
    – Siddharth
    May 30, 2017 at 14:18
15

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.

5

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.

0
2

Better and simple:

tail -f log.txt | egrep -m 1 "error"
echo "Found error, do sth."
...
1
  • 2
    Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Jul 26, 2017 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.