Web 2.0 网站架构、优化 数据库架构
标签类目:php

用syslog-ng实时收集每一行php报错

收集PHP的每一个报错信息.最终的方案如下:

1.安装syslog-ng,修改配置文件vim /etc/syslog-ng/syslog-ng.conf ,加上这几行:

source s_phplog { file(“/home/x/logs/php/php.www.log”);};
destination d_php_tomail { program(“/home/x/bin/send_my_mail.py”);};
log { source(s_phplog);destination(d_php_tomail);};

这几行配置就是让syslog-ng来监控php日志输出,然后每当有日志输出,就启动我写好的一个脚本文件,让它来发送到我的邮箱.send_my_mail.py内容很简单:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#导入smtplib和MIMEText
import smtplib
from email.mime.text import MIMEText
#############
#要发给谁,这里发给2个人
#####################
#设置服务器,用户名、口令以及邮箱的后缀
mail_host="smtp.****.com"
mail_user="noreply@example.com"
mail_pass="****"
######################
def send_mail(to_list,sub,content):
    '''
    to_list:发给谁
    sub:主题
    content:内容
    send_mail("aaa@126.com","sub","content")
    '''
    msg = MIMEText(content)
    msg['Subject'] = sub
    msg['From'] = mail_user
    msg['To'] = ";".join(to_list)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(mail_user, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False
if __name__ == '__main__':
    mailto_list=["renlu.xu@xiaoqianbao.com"]
    lines = raw_input()
    if send_mail(mailto_list,"发生了错误",lines):
        print "发送成功"
    else:
        print "发送失败"

就是从标准输入中读到内容,然后发送到邮箱.我就是从网上扒了段代码,都没细读.

然后重启syslog-ng:

sudo /etc/init.d/syslog-ng

就可以了.我把这个日志设置为发送到了qq邮箱,然后用微信接收,就实现了服务器的实时报警.

但是后来发现,一些日志,发过来的,完全没法查是怎么出问题了,比如如报警是undefined function init_framework() called这种,连我初始化函数都没有加载,我都不知道这程序从哪儿开始执行的了….于是决定小改造一下,在有严重的出错信息时,将当前的URI信息记录到errorlog中.就有了这么一段代码,插入到php文件的开头了:


PHP+Tidy-完美的XHTML纠错+过滤

          function HtmlFix( $html ) {
		if (!function_exists('tidy_repair_string'))
			return $html;
			//repair
		$str = tidy_repair_string($html, array(
			'output-xhtml' => true
		), 'utf8');
		//parse
		$str = tidy_parse_string($str, array(
			'output-xhtml' => true
		), 'utf8');
		$s = '';
		$nodes = @tidy_get_body($str)->child;
		if (!is_array($nodes)) {
			$returnVal = 0;
			return $s;
		}
		foreach ($nodes as $n) {
			$s .= $n->value;
		}
		return $s;
	}

转载:http://hi.baidu.com/aohaiyixiao1/blog/item/c93ad9d3e364b6d5a8ec9a53.html

官方:http://tidy.sourceforge.net/

返回顶部