Anton Krall
Anton Krall

Reputation: 45

Tail a log file on linux and trigger a script if words are matched

I'm looking for a way to watch multiple logfiles on linux and look for words or phrases inside and if found, trigger a script or action, this will need to be constant.

I know this can be done with some grep, tail hack but I want to know if there is something premade for this with config options, for instance, I think logtail can monitor files but can't trigger actions.

Any ideas?

Upvotes: 0

Views: 2803

Answers (2)

Anton Krall
Anton Krall

Reputation: 45

The answer is SEC (yum install sec). What it does is that it monitors any log file and uses rules to scan the files using regex and then you can run shell scripts, insert logs, and some other stuff.

It runs as a service so no problem with machine reboots, crons, etc.

Hope this helps anybody trying to do what I wanted.

Upvotes: 0

nDCasT
nDCasT

Reputation: 71

You can set the output of the grep to a variable and then evaluate if its empty to run your script/actions.

Example:

Convert command output to string with $( whatever command )
line=$(  grep -m 1 YourKeyWord <( exec tail -f /directory/of/log.out ); kill $! 2> /dev/null)
Then you can start evaluating each log, and determine the following actions.
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

You can do this with two functions (one to reset $line, and other to do the grep, using a $Dir var) but for the sake of the detailed answer , let's leave this way.

The line,

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

was taken from the answer https://superuser.com/questions/275827/how-to-read-one-line-from-tail-f-through-a-pipeline-and-then-terminate with the following explanation, and it does avoid logical issues in your server.

"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."

Upvotes: 1

Related Questions