• 技术文章 >后端开发 >php教程

    PHP5下的Error错误处理及问题定位的介绍(代码示例)

    不言不言2019-01-09 10:38:10转载1458
    本篇文章给大家带来的内容是关于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
         */
        static public function packData($params, $status = 0)
        {
            $res['status'] = $status;
            $res['data'] = json_encode($params);
            return $res;
        }
    
    }

    其中json_encode那一行报错了,然后你查了下packData这个方法,有很多项目的类中都有调用,这时要怎么定位问题呢?

    场景复现

    好,首先我们复现下场景。假如实际调用的程序bug.php如下

    <?php
    
    require_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);
            }
    
        }
    
    }

    再次运行bug.php,日志如下。

    error_get_last:array (
      'type' => 1,
      'message' => 'Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes)',
      'file' => '/CommonReturn.class.php',
      'line' => 23,
    )
    trace:#0  CommonReturn::handleFatal()

    回溯信息没有来源,尴尬了。猜测因为backtrace信息保存在内存中,当出现致命错误时会清空。没办法,把backtrace从外面传进来试试。再次修改CommonReturn.class.php。

    <?php
    
    /**
     * 公共返回封装
     * Class CommonReturn
     */
    class CommonReturn
    {
    
        /**
         * 打包函数
         * @param     $params
         * @param int $status
         *
         * @return mixed
         */
        static public function packData($params, $status = 0)
        {
    
            ob_start();
            debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
            $trace = ob_get_clean();
            register_shutdown_function(['CommonReturn', 'handleFatal'], $trace);
    
            $res['status'] = $status;
            $res['data'] = json_encode($params);
            return $res;
        }
    
        /**
         * 错误处理
         * @param $trace
         */
        static protected function handleFatal($trace)
        {
            $err = error_get_last();
            if ($err['type']) {
                $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);
            }
    
        }
    
    }

    再次运行bug.php,日志如下。

    error_get_last:array (
      'type' => 1,
      'message' => 'Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes)',
      'file' => '/CommonReturn.class.php',
      'line' => 26,
    )
    trace:#0  CommonReturn::packData() called at [/bug.php:13]

    成功定位到了调用来源,在bug.php的13行。将最终的CommonReturn.class.php发布到生产环境,再次出现出现错误时候看日志就可以了。但是这样的话所有调用packData的程序都会执行trace函数,肯定也会影响性能的。

    总结

    1. 对于其中使用到的register_shutdown_function函数需要注意,可以注册多个不同的回调,但是如果某一个回调函数中exit了,那么后面注册的回调函数都不会执行。

    2. debug_print_backtrace这个获取回溯信息函数第一个是否包含请求参数,第二个是回溯记录层数,我们这里是不返回请求参数,可以节省些内存,而且如果请求参数巨大的话调这个函数可能就直接内存溢出了。

    1. 最好的办法就是升级PHP7,可以像异常一样捕获错误。

    以上就是PHP5下的Error错误处理及问题定位的介绍(代码示例)的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:segmentfault.,如有侵犯,请联系admin@php.cn删除
    专题推荐:php
    上一篇:PHP面试中正则表达式的知识总结(超详细) 下一篇:php读取CSV文件的方法介绍(代码示例)
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【活动】充值PHP中文网VIP即送云服务器• 在Win2003(64位)中配置IIS6+PHP5.2.17+MySQL5.5的运行环境_php技巧• PHP5.2中PDO的简单使用方法_php技巧• 解决更换PHP5.4以上版本后Dedecms后台登录空白问题的方法_php技巧• PHP5.2下preg_replace函数的问题_php技巧• php5.4以上版本GBK编码下htmlspecialchars输出为空问题解决方法汇总_php技巧• Linux下php5.4启动脚本_php技巧• PHP5.5和之前的版本empty函数的不同之处_php技巧
    1/1

    PHP中文网