为什么 PHP 错误打印两次?

2022-08-30 12:43:08

总结

令人惊讶的是,我在Google或SO上找不到任何关于此的内容。当我在PHP中抛出异常时,它会在我的控制台中出现两次,并带有错误消息和堆栈跟踪。第一次打印时,它说“PHP致命错误:...”第二次它只是说“致命错误:...”。我还没有测试这是Apache插件版本。

使用一些命名空间和路径缩短为“...”为了安全:

$ php code/com/.../tabular_data.php
PHP Fatal error:  Uncaught exception 'Exception' with message 'File type not supported' in /home/codemonkey/.../tabular_data.php:56
Stack trace:
#0 /home/codemonkey/.../tabular_data.php(88): com\...\Tabular_Data->loadFromFile('/home/codemonke...', false)
#1 /home/codemonkey/.../tabular_data.php(95): com\...\Tabular_Data::fromFile('/home/codemonke...')
#2 {main}
  thrown in /home/codemonkey/.../tabular_data.php on line 56

Fatal error: Uncaught exception 'Exception' with message 'File type not supported' in /home/codemonkey/.../tabular_data.php:56
Stack trace:
#0 /home/codemonkey/.../tabular_data.php(88): com\...\Tabular_Data->loadFromFile('/home/codemonke...', false)
#1 /home/codemonkey/.../tabular_data.php(95): com\...\Tabular_Data::fromFile('/home/codemonke...')
#2 {main}
  thrown in /home/codemonkey/.../tabular_data.php on line 56

问题

我认为它与stderr和stdout都打印错误有关。无论如何,我如何要求PHP只打印一次,最好是stderr?


版本输出

PHP 5.3.9 (cli) (已建設: Jan 11 2012 17:09:48)
Copyright (c) 1997-2012 PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies

代码


http://pastebin.com/iBUGJ2eY 这是为我显示双重异常的确切代码,命名空间和路径已编辑为foos。请注意,在此安装中,我总是在命令行中收到双重异常。我几乎可以肯定,问题在于PHP配置。


答案 1

复制了它。第一条错误消息是设置的结果,并转到 。log_errorsSTDERR

第二个是 的结果,转到 。display_errorsSTDOUT

这两个设置都可以在运行时进行更改。因此,为了“好好地询问PHP”,这就足够了:

ini_set('log_errors', 1);
ini_set('display_errors', 0);

答案 2

就像Linus Kleen的答案中所写的那样,双重消息的原因是去stdout。我发现从php 5.2.4开始,当设置为1或“on”时,甚至会发生这种情况。display_errorsdisplay_errors

要恢复正常行为,这是定义应存储记录错误的文件的最佳方法,例如添加以下内容:

error_log = 'd:/logs/php_error.log'

到你的 php.ini。定义error_log的文件后,您只会收到一条消息,以 stdout 测试所需的内容。对于生产状态,可以设置为 0。display_errors


推荐