19

是否可以记录 php 警告的堆栈跟踪?还是抓住一个警告和error_log()?

在我的错误日志中有一些导致警告的代码,但是如果不知道堆栈跟踪,就不可能知道是什么导致了这些警告。

4

4 回答 4

15

有一个与 toset_error_handler()结合使用的示例ErrorException

https://php.net/manual/en/class.errorexception.php

您只需要在处理程序函数中实现您的自定义日志记录功能。


更新:

请注意,这也适用于警告和许多其他错误类型。如需完全兼容,请参阅以下手册set_error_handler()

https://php.net/set_error_handler

于 2011-06-21T14:19:01.983 回答
12

只需在脚本的开头抛出这个:

set_error_handler(function($severity, $message, $file, $line) {
    if (error_reporting() & $severity) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
});

删除if您想要记录的所有内容,即使它被禁止。

于 2016-06-14T21:16:20.263 回答
1

我相信如果您在 php.ini 文件中启用了 xdebug,它会记录日志,但它具有堆栈跟踪(具有一些额外功能,例如显示局部变量)。但不推荐用于生产环境。

XDebug 堆栈跟踪

于 2011-06-21T14:31:27.350 回答
1

干得好:

class WarningWithStacktrace extends ErrorException {}
set_error_handler(function($severity, $message, $file, $line) {
    if ((error_reporting() & $severity)) {
        if ($severity & (E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE)) {
            $ex = new WarningWithStacktrace($message, 0, $severity, $file, $line);
            echo "\n" . $ex . "\n\n";
            return true;
        } else {
            throw new ErrorException($message, 0, $severity, $file, $line);
        }
    }
});

像往常一样抛出错误/异常,仅打印通知/警告。

PS:严格和其他警告级别没有解决,如果需要修改代码...

于 2019-12-09T08:26:05.323 回答