项目上线后,都会使用一些异常监控,当然很多时候监控是有限制的,比如要监控PHP异常,类似这种一般都在输出人性化内容而不是直接输出错误内容,很多时候需要捕捉这类异常来进行代码调整。当然也可以定期去查看日志。


laravel5支持自定义异常处理,给这种需求提供了方便,我们完全可以扩展异常处理,通过发送邮件或短信。

打开 app/Exceptions/Handler.php 文件,修改 render 函数代码,增加发送邮件通知功能:

if(!$einstanceof\Symfony\Component\Debug\Exception\FlattenException){$e=\Symfony\Component\Debug\Exception\FlattenException::create($e);}$exception=new\Symfony\Component\Debug\ExceptionHandler();$content=$exception->getContent($e);$css=$exception->getStylesheet($e);\Mail::queue('errors.mail',['url'=>$request->fullUrl(),'request'=>$request->all(),'method'=>$request->getMethod(),'header'=>$request->header(),'content'=>$content,'css'=>$css],function($message){$message->to('name@admin.com')->cc('name1@admin.com')->subject('程序异常');});

原来的

returnparent::render($request,$e);

是返回异常内容或403页面的,如果想页面返回更友好,可以去掉这个代码改成其它内容返回,可直接使用如形式的代码:

returnresponse('服务器累了,稍后再试!');


邮件模板:

<HTML><HEAD><TITLE>系统异常,请及时维护!</TITLE><metahttp-equiv="content-type"content="text/html;charset=utf-8"><STYLE>html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h2,h3,h4,h5,h6,h7,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}html{background:#eee;padding:10px}img{border:0;}#sf-resetcontent{width:970px;margin:0auto;}{!!$css!!}</style></HEAD><BODY><h3>请求地址:</h3>{{$url}}&nbsp;&nbsp;&nbsp;<h3>请求方式:</h3>{{$method}}<h3>请求参数:</h3><pre>{{var_export($request,true)}}</pre><h3>请求头信息:</h3><pre>{{var_export($header,true)}}</pre><h3>异常内容:</h3><pre>{!!$content!!}</pre></BODY></HTML>


注意:邮件是通过队列发送的,以减少页面响应速度,实际使用时需要开启队列处理命令。


开启队列处理命令方法:

直接添加定时命令到 crontab

crontab-e

*****phpartisanqueue:work1>>/dev/null2>&1#启动队列监听

写到框架的 schedule 中,然后通过 schedule 模拟crontab定时处理内部所有命令

打开 app/Console/Kernel.php 文件在 schedule 函数下添加代码:

//监听队列

$schedule->command('queue:work',$parameters)->everyMinute()->withoutOverlapping();

然后添加定时命令:

crontab-e

*****phpartisanschedule:run1>>/dev/null2>&1#启动schedule