项目上线后,都会使用一些异常监控,当然很多时候监控是有限制的,比如要监控PHP异常,类似这种一般都在输出人性化内容而不是直接输出错误内容,很多时候需要捕捉这类异常来进行代码调整。当然也可以定期去查看日志。
laravel5支持自定义异常处理,给这种需求提供了方便,我们完全可以扩展异常处理,通过发送邮件或短信。
打开 app/Exceptions/Handler.php 文件,修改 render 函数代码,增加发送邮件通知功能:
if (!$e instanceof \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('程序异常');
});
原来的
return parent::render($request, $e);
是返回异常内容或403页面的,如果想页面返回更友好,可以去掉这个代码改成其它内容返回,可直接使用如形式的代码:
return response('服务器累了,稍后再试!');
邮件模板:
<HTML>
<HEAD>
<TITLE>系统异常,请及时维护!</TITLE>
<meta http-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:0 auto; }
{!!$css!!}
</style>
</HEAD>
<BODY>
<h3>请求地址:</h3>
{{$url}}
<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
* * * * * php artisan queue:work 1>> /dev/null 2>&1 #启动队列监听
写到框架的 schedule 中,然后通过 schedule 模拟crontab定时处理内部所有命令
打开 app/Console/Kernel.php 文件在 schedule 函数下添加代码:
//监听队列
$schedule->command('queue:work',$parameters)
->everyMinute()
->withoutOverlapping();
然后添加定时命令:
crontab -e
* * * * * php artisan schedule:run 1>> /dev/null 2>&1 #启动schedule
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。