今日在开发中,遇到线上服务器不记录变量不存在的错误日志,那么是怎么回事呢?
于是开始查找 index.php 中的代码switch (ENVIRONMENT) {
case 'development':
error_reporting(-1);
ini_set('display_errors', 0);
break;
case 'testing':
case 'production':
ini_set('display_errors', 0);
if (version_compare(PHP_VERSION, '5.3', '>=')) {
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
}
else {
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
}
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'The application environment is not set correctly.';
exit(1); // EXIT_ERROR
}
线上代码是 production 生产环境, 是执行:error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
这句话的代码是什么意思呢?
所有日志,除了了E_NOTICE E_STRICT 以及E_USER_NOTICE 这三个错误以外的错误才提示和记录,
变量不存在,属于 Notice 这个层次的
开发环境:可以正常记录,变量不存在
ERROR - 2018-06-12 17:29:58 --> Severity: Notice --> Undefined index: success D:\phpStudy\WWW\jifen\wangyu\app\helpers\funs_helper.php 158
生产环境:不记录了
原因就是:error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
打开错误:
打开所有的错误,全部输出:这是开发环境
ini_set('display_errors',1);
error_reporting(-1); 报告所有的错误
error_reporting(0); //关闭所有错误
error_reporting=E_ALL & ~E_NOTICE
意思是报告所有的错误,但除了E_NOTICE这一种。这也是最常用的错误报告级别,它不会报告注意类(如:使用了未定义的变量)的错误。
下面列举一些错误报告级别:
值 常量 说明
1 E_ERROR 报告导致脚本终止运行的致命错误
2 E_WARNING 报告运行时的警告类错误(脚本不会终止运行)
4 E_PARSE 报告编译时的语法解析错误
8 E_NOTICE 报告通知类错误,脚本可能会产生错误
32767 E_ALL 报告所有的可能出现的错误(不同的PHP版本,常量E_ALL的值也可能不同)
error_reporting(E_ALL ^ E_NOTICE); // 除了E_NOTICE之外,报告所有的错误
error_reporting(E_ALL & ~E_NOTICE); // 除了E_NOTICE之外,报告所有的错误 这两种意思一样
error_reporting(E_ERROR); // 只报告致命错误
echo error_reporting(E_ERROR | E_WARNING | E_NOTICE); // 只报告E_ERROR、E_WARNING 和 E_NOTICE三种错误
注意:配置文件php.ini中display_errors的默认值为On,代表显示错误提示,如果设置为Off,就会关闭所有的错误提示。
可以通过程序动态去设置 错误是否开启和关闭:ini_set('display_error');
ini_get('display_errors'); 可以获取当前php运行 错误报告的状态。
特别告知: Notice 和 Warning 运行出错的时候,程序不会停止,会继续运行。
class Err{
protected $debug;
public function __construct($debug=true){
$this->debug=$debug;
}
public function error(){
error_reporting(0);
set_error_handler([$this,'handle'],E_ALL|E_STRICT);
}
public function handle($code,$error,$file,$line){
echo $error;
print_r($file);
}
}
(new Err())->error();
echo $a;