Question

Script that will email the last few lines of error logs ..

I am working on a script that:

  • checks if mysql and apache are running
  • if not, it sends an email and then attempts to restart the non-running service

I would like to add the last few lines of the error logs to the email. Here is what I have so far. The check works, the restart works, sending email works, but am not getting my error messages from the log:

#!/bin/bash
#ver. 1 

##this script will check mysql and apache
##if that service is not running
##it will start the service and send 
##an email to you

##set your email address 
EMAIL="email@yourdomain.com"

##list your services you want to check
SERVICES=(  'mysql' 'apache2' )

#### DO NOT CHANGE anything BELOW ####

 for i in "${SERVICES[@]}"
  do
    ###IF APACHE IS NOT RUNNING####
     if [[  "$(service $i status)" =~ "not"  ]]
	then
	service $i start
	MESSAGE= "$(tail -5 /var/log/$i/error.log)"
	SUBJECT="$i down on $(hostname) $(date) "
	echo "$MESSAGE   mysql" | mail -s "$SUBJECT" "$EMAIL"
     fi
    ###IF MYSQL IS NOT RUNNING####
     if [[  "$(service $i status)" =~ "stop" ]]
	then
	service $i start
	MESSAGE= "$(tail -5 /var/log/$i/error.log)"
	SUBJECT="$i down on $(hostname) $(date) "
	echo "$MESSAGE " | mail -s "$SUBJECT" "$EMAIL"
     fi
  done

Any tips on getting info from the error logs into the email? Also, my loop would be much better if all services had the same status message…I wonder if there is a better way of checking if the service is running that will return the same result for all services.

Show comments

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

For checking if the service is running or not, you could check the exit code. A well written init script should return 0 if the service is good, 1 service is dead but the /var/run pid file exists, and 3 if it is not running at all. Like:

$ service apache2 status; echo $?
 * apache2 is running
0
$ service apache2 stop
 * Stopping web server apache2
$ service apache2 status; echo $?
 * apache2 is not running
3