在ejabberd服务器的二次开发当中,自己写的代码难免会发生错误。下面通过一个简单的脚本在,ejabberd发生错误的时候。error.log中的最新的错误内容以邮件的方式发送到你指定的邮箱中,下面是脚本的内容:
#!/bin/bash
##
## Auther: quanzhuo
## Date: 2015/5/14
##
## This script check the ejabberd logs to find out if there is any
## new errors occured in ejabberd server. If that, the script will
## mail the exact error content to the the mail address specified
## Mandatory root to exec this script
if [ $(id -g) -ne 0 ]; then
echo "This script must be executed by root"
exit 1
fi
## Default arguments if not specified in command line
ADDRS=380317031@qq.com,jimmy.jp.chen@foxconn.com
LOG_DIR=/opt/ejabberd/var/log/ejabberd
BACKUP_DIR=/root/.error_logs
## Display the help info
help()
{
echo "Usage: error_report [-adh]"
echo "-a \"addr\""
echo -n "--address \"addr\""
echo " addr is address that the mail send to, default to 380317031@qq.com"
echo "-d \"dir\""
echo -n "--directory \"dir\""
echo " dir is the log directory, default to /opt/ejabberd/var/log/ejabberd"
echo "-h"
echo "--help display this help and exit"
echo ""
}
## Parse command line arguments
while [ $# -ne 0 ];
do
PARAM=$1
shift
case $PARAM in
-a)
ADDRS=$1
shift
;;
--address)
ADDRS=$1
shift
;;
-d)
LOG_DIR=$1
shift
;;
--directory)
LOG_DIR=$1
shift
;;
-h)
help
exit 0
;;
--help)
help
exit 0
;;
*)
echo "BAD arguments"
help
exit 1
;;
esac
done
## compare the old log and the new log
if [ -f $BACKUP_DIR/backup_log ];then
for log in $(ls $LOG_DIR/error.log* | sort -rn)
do
cat $log >> $BACKUP_DIR/new_log
done
diff $BACKUP_DIR/backup_log $BACKUP_DIR/new_log &> /dev/null
if [ $? -ne 0 ];then
diff $BACKUP_DIR/backup_log $BACKUP_DIR/new_log | tail -n +2 | cut -c 3- >> $BACKUP_DIR/new_errors
rm -rf $BACKUP_DIR/backup_log
mv $BACKUP_DIR/new_log $BACKUP_DIR/backup_log
else
rm -rf $BACKUP_DIR/new_log
fi
else
mkdir -p $BACKUP_DIR
for log in $(ls $LOG_DIR/error.log* | sort -rn)
do
cat $log >> $BACKUP_DIR/backup_log
done
cp $BACKUP_DIR/backup_log $BACKUP_DIR/new_errors
fi
if [ -f $BACKUP_DIR/new_errors ];then
mail -s "New errors occured in ejabberd" $ADDRS < $BACKUP_DIR/new_errors &> /dev/null
echo "report errors at: $(date)" >> $BACKUP_DIR/report_log
cat $BACKUP_DIR/new_errors >> $BACKUP_DIR/report_log
rm -rf $BACKUP_DIR/new_errors
fi
用法:
error_report接受三个参数:
-a/--address:指定邮件通知的邮箱地址,支持多个邮箱,邮箱之间用逗号分隔,不能有空格。
-d/--directory:指定你的ejabberd的log的所在路径,默认为/opt/ejabberd/var/log/ejabberd
-h/--help:显示帮助信息
将该脚本放在你的主机的某一个目录下如:/root/bin。
赋予其可执行权限。
然后在crontab中添加一条例行性任务即可。
比如:
输入crontab -e打开crontab进行编辑,如果每隔5分钟检测一次有没有新的error发生:
*/5 * * * * /root/bin/error_report -a 380317031@qq.com,yourmail@qq.com