php 异常处理函数 register_shutdown_function

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/simplexingfupeng/article/details/80555834

register_shutdown_function() 表示 PHP 在程序结束时触发某个函数行为。

如果仅仅是打印 log 日志,我们在php.ini文件中 log_error 开启,即可写入日志。
此注册函数是为了其他行为的方便操作,比如出现错误后程序自动抓取程序错误发送给管理员邮件或者短信功能。

程序结束有四种情况:

  • php代码执行过程中发生错误
  • php代码顺利执行成功
  • php代码运行超时
  • 页面被用户强制停止

以下情况不会执行回调函数:

  • 程序有语法错误;
  • 调用register_shutdown_function函数调用之前发生了致命错误;
  • 调用register_shutdown_function()函数之前有exit()函数调用,register_shutdown_function()函数将不能执行;

我们自定义一个行为:

<?php
/**
 * Created by PhpStorm.
 * User: Xavier
 * Date: 2018/6/3
 * Time: 12:16
 */
class RegisterShutDownFunction
{
    /**
     * @author Xavier
     * @desc php 程序运行结束时候需要运行的函数
     */
    public static function register()
    {
        if ($error = error_get_last()) {
            // $filename 必须是一个绝对路径
            if (!defined('REGISTER_SHUTDOWN_FUNCTION_LOG_FILENAME')) {
                $filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'register_shutdown_function.log';
            } else {
                $filename = REGISTER_SHUTDOWN_FUNCTION_LOG_FILENAME;
            }
            $message = '时间 : ' . date('Y-m-d H:i:s') . PHP_EOL;
            $message .= '文件 : ' . $error['file'] . PHP_EOL;
            $message .= '行数 : ' . $error['line'] . PHP_EOL;
            $message .= '错误 : ' . $error['message'] . PHP_EOL;
            $message .= '类型 : ' . $error['type'] . PHP_EOL . PHP_EOL;
            file_put_contents($filename, $message, FILE_APPEND);
        }
    }
}

接下来应用:

<?php
/**
 * Created by PhpStorm.
 * User: Xavier
 * Date: 2018/6/3
 * Time: 12:27
 */
 // 定义一个常量来记录程序停止后,出现错误的 LOG 日志文件
define('REGISTER_SHUTDOWN_FUNCTION_LOG_FILENAME', dirname(__FILE__) . DIRECTORY_SEPARATOR . '11.log');
// 包含异常处理的类文件
include 'lib/RegisterShutDownFunction.php';
$registerShutDownFunction = new RegisterShutDownFunction();
// register_shutdown_function 函数必须在所有的程序执行之间注册
register_shutdown_function(array($registerShutDownFunction, 'register'));

// 注册成功之后调用一个不存在的方法 aa();
aa();

错误日志:

时间 : 2018-06-03 04:56:02
文件 : /Users/x/www/php/exception/2.php
行数 : 17
错误 : Uncaught Error: Call to undefined function aa() in /Users/x/www/php/exception/2.php:17
Stack trace:
#0 {main}
  thrown
类型 : 1

错误日志中的类型为错误级别,可以参照PHP报错级别对照表

猜你喜欢

转载自blog.csdn.net/simplexingfupeng/article/details/80555834