【问题标题】:Extending the default php errors and error_log扩展默认的 php 错误和 error_log
【发布时间】:2017-02-23 21:49:15
【问题描述】:

我想知道是否有人知道如何更改 PHP 中记录错误消息的默认方式。希望这可以应用于所有消息、致命错误、警告等,以及我的脚本在任何时候调用 error_log。

目前默认的错误信息在日志中显示为

[19-Feb-2017 15:38:42 America/Vancouver] Could not post employee data - no rows submitted
[20-Feb-2017 11:12:34 America/Toronto] PHP Warning:  array_splice() expects parameter ...

但是对我来说非常有益的是,如果我可以让它还包含我为每个用户存储在$_SESSION 中的一些变量,例如用户的登录名和公司。因此,例如错误可能会输出如下

[19-Feb-2017 15:38:42 America/Vancouver] [CompanyXYZ/bob_smith] Could not post employee data - no rows submitted
[20-Feb-2017 11:12:34 America/Toronto] [OtherCompany/jimbo_redneck] PHP Warning:  array_splice() expects parameter ...

PHP 世界中是否存在类似的东西?

【问题讨论】:

  • Could not post employee data - no rows submitted 来自哪里?这不是 PHP 错误。无论在哪里生成,都在那里添加其他变量。
  • 对不起,我应该澄清错误消息,这是我自己使用 error_log 的错误消息。我的项目到处都是它们,我希望 php 有办法修改默认错误消息和我自己的,而不必重写每个 error_log 实例。

标签: php error-log


【解决方案1】:

您可以create your own error handling routine。您应该能够将所需的任何数据添加到错误消息中。这样的事情应该让你开始:

<?php
function my_handler($errno , $errstr, $errfile, $errline, $errcontext)
{
    $msg = "Hey I got an error of type $errno ($errstr) from $errfile line $errline!";
    $msg .= "Here's some more info: $_SESSION[foo]";
    error_log($msg);
    return true;
}
set_error_handler("my_handler");

致命错误仅由语法错误等代码问题引起。它们不会发生在用户身上,因此您不必担心会抓住它们。

注意things change considerably in PHP 7

【讨论】:

  • 嘿,谢谢,我想我完全忽略了这个功能!如果我理解正确,在实现自定义错误处理程序后,我是否应该在我的项目中使用 trigger_error("Oh no an error in ...") 而不是 error_log("Oh no an error in ...") 让它不绕过自定义处理程序?
  • error_log() 只是直接写入日志文件,所以是的 trigger_error() 将是您在这里寻找的,如果您想记录 PHP 不考虑的“错误”错误,并让它通过您的自定义处理程序。
猜你喜欢
  • 1970-01-01
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
相关资源
最近更新 更多