本篇文章给大家带来的内容是关于PHP5下的Error错误处理及问题定位的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
来说说当PHP出现E_ERROR级别致命的运行时错误的问题定位方法。例如像Fatal error: Allowed memory size of
内存溢出这种。当出现这种错误时会导致程序直接退出,PHP的error log中会记录一条错误日志说明报错的具体文件和代码行数,其它的任何信息都没有了。如果是PHP7的话还可以像捕获异常一样捕获错误,PHP5的话就不行了。
一般想到的方法就是看看报错的具体代码,如果报错文件是CommonReturn.class.php像下面这个样子。
<?php/** * 公共返回封装 * Class CommonReturn */class CommonReturn{ /** * 打包函数 * @param $params * @param int $status * * @return mixed */ s<div>)本文来源gaodai.ma#com搞#代!码网_</div><strong>搞代gaodaima码</strong>tatic public function packData($params, $status = 0) { $res['status'] = $status; $res['data'] = json_encode($params); return $res; }}
其中json_encode那一行报错了,然后你查了下packData这个方法,有很多项目的类中都有调用,这时要怎么定位问题呢?
场景复现
好,首先我们复现下场景。假如实际调用的程序bug.php如下
<?phprequire_once './CommonReturn.class.php';$res = ini_set('memory_limit', '1m');$res = [];$char = str_repeat('x', 999);for ($i = 0; $i < 900 ; $i++) { $res[] = $char;}$get_pack = CommonReturn::packData($res);// something else
运行bug.php PHP错误日志中会记录
[08-Jan-2019 11:22:52 Asia/Shanghai] PHP Fatal error: Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes) in /CommonReturn.class.php on line 20
复现成功,错误日志中只是说明了报错的文件和哪行代码,无法知道程序的上下文堆栈信息,不知道具体是哪块业务逻辑调用的,这样一来就无法定位修复错误。如果是偶尔出现,并且没有来自前端业务的反馈要怎么排查呢。
解决思路
1、有人想到了修改memory_limit增加内存分配,但这种方法治标不治本。做开发肯定要找到问题的根源。
2、开启core dump,如果生成code文件可以进行调试,但是发现code只有进程异常退出才会生成。像E_ERROR级别的错误不一定会生成code文件,内存溢出这种可能PHP内部自己就处理了。
3、使用register_shutdown_function注册一个PHP终止时的回调函数,再调用error_get_last如果获取到了最后发生的错误,就通过debug_print_backtrace获取程序的堆栈信息,我们试试看。
修改CommonReturn.class.php文件如下
<?php/** * 公共返回封装 * Class CommonReturn */class CommonReturn{ /** * 打包函数 * @param $params * @param int $status * * @return mixed */ static public function packData($params, $status = 0) { register_shutdown_function(['CommonReturn', 'handleFatal']); $res['status'] = $status; $res['data'] = json_encode($params); return $res; } /** * 错误处理 */ static protected function handleFatal() { $err = error_get_last(); if ($err['type']) { ob_start(); debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5); $trace = ob_get_clean(); $log_cont = 'time=%s' . PHP_EOL . 'error_get_last:%s' . PHP_EOL . 'trace:%s' . PHP_EOL; @file_put_contents('/tmp/debug_' . __FUNCTION__ . '.log', sprintf($log_cont, date('Y-m-d H:i:s'), var_export($err, 1), $trace), FILE_APPEND); } }}