How to automatically generate logs and e-mail them |
| Written by Michael D. | |
|
In this tutorial, I will explain how to create a central log file with all information you need at a specific time, store it or e-mail it. This can be acomplished with some basic Linux shell commands and some small tools that are generally avaiable in any system. First of all, create a directory somewhere on your hard drive where you want to store all generated logs. Let's say you pick and create /stats.
Now you have to create a crontab on the root account (with the command crontab -e).
For example if you enter the command "ifconfig eth0 > outputfile.log", any data comming from the command will be written in that file (viewed in shell with the 'more' command):
As you can see, if I reuse the same file name with other command, I will rewrite the file. This is not very useful in our case, so we'll use the ">>" option:
[root@LinuxSrv /]# ifconfig eth0 >> outputfile.log
PID TTY TIME CMD
In the crontab, write the command outputs for anything you want to log; for pasting from other log files, the usage is the same.
The cron config should be like this:
You may want to add some blank lines between the commands or words, so use the 'echo' command like in the example above. 00 06 * * * mail -s "MY log on `date`" youruser@yourdomain < /stats/systemlog This command will send a mail with the subject "My log on <current_full_date> that will include the file /stats/systemlog. To prevent writing and resending the same file every morning, rename the file after e-mailing it. A date-related name is useful in organizing your data: 01 06 * * * mv /stats/systemlog "/stats/systemlog_`date`" This will rename your file according to the current date, making it something like "systemlog_Sat Sep 05 06:01:01 EEST 2007"; sometimes the shell will replace the spaces with "\" sign for some reason.
If your server is not online or is shutdown at the time when the crontab should execute, the result will depend of your running configuration. If you are running anacron at system startup for example, it will execute unfinished cron tasks due to downtime, writing the logs and sending the mail at bootup. If your Linux box was not online at 6.00 am when the sendmail tried to send the data, it will retry by default for 5 days to resend it. Another issue that you should be aware of is the configuration of the sendmail service (usually /etc/mail/sendmail.cf). If it's not configured properlly or your server doesn't have a valid domain name, the sent e-mail could end up being treated as spam by the mail server (being considered to come from localhost.localdomain). You can still configure a filter on most mailing providers to overcome this. Hope this was useful
Do you need more help? Ask now!
|
|
| Last Updated ( Wednesday, 05 September 2007 ) |