I had a use case where I wanted to be notified whenever a particular string occured in a log file. This seemed a bit overkill to make a custom implementation in a monitoring solution, so I wrote a simple Bash script to send me a push notification whenever it occurs.
There’s a bit of logic in there to prevent it from spamming me every time the string is found, it will instead only notify me once every hour if the string is still present.
The full notification script
Let’s start with this one first, here’s the full script that now runs in a cronjob every minute.
#!/bin/bash
RESULT=$(grep -c 'keyword' /path/to/file.log 2>/dev/null)
if [ "$RESULT" -gt "0" ]; then
TIMESTAMPFILE="/path/to/timestamp.txt"
TIMESTAMPLASTMODIFIED=$(stat -c %y "TIMESTAMPFILE")
CURRENTTIME=$(date +%s)
TIMEDIFF=$(expr $CURRENTTIME - $TIMESTAMPLASTMODIFIED)
if [ $TIMEDIFF -gt "3600" ]; then
curl -X POST --data "apikey={YOUR_API_HERE}" --data "priority=high" --data "event=log entry found" --data "application=LogSearcher" https://api.prowlapp.com/publicapi/add
touch $TIMESTAMPFILE
fi
fi
Some more details
I use a service called Prowl App that has a simple API that allows me to send a message to it using curl
. This is the part that handles the push notification.
The actual check is in the grep -c 'keyword' /path/to/file.log
command. If the string “keyword” is found in the log “file.log”, it will count the occurences. If none are found, it’ll be 0.
Next we check if the results have more than 0, using the if [ "$RESULT" -gt "0" ]
construct.
Once that’s the case, we identify a “timestamp file”: this will be used as a sort-of locking mechanisme, to only notify me once every hour. If a push notification was fired, I update the lock file with touch
to bump its last-modified date to now.
Next time the script runs, the time check will fail, and it will not send me a push notification anymore.
Here’s what it looks like if it fires:
You can modify that payload as you see fit, of course.