我正在尝试使用 register_shutdown_function 和 set_error_handler 函数记录错误。我正在使用以下类文件。但它不起作用。
<?php
//Logs.php
class MyLogs
{
public function __construct()
{
register_shutdown_function(array($this, 'shutdownHandler'));
set_error_handler(array($this, 'errorHandler'));
}
private function errorHandler($error_level, $error_message, $error_file, $error_line, $error_context)
{
$error = "lvl: " . $error_level . " | msg:" . $error_message . " | file:" . $error_file . " | ln:" . $error_line;
switch ($error_level) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_PARSE:
case E_USER_ERROR:
$this->logMe($error, "fatal");
break;
case E_USER_ERROR:
case E_RECOVERABLE_ERROR:
$this->logMe($error, "error");
break;
case E_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_USER_WARNING:
$this->logMe($error, "warn");
break;
case E_NOTICE:
case E_USER_NOTICE:
$this->logMe($error, "info");
break;
case E_STRICT:
$this->logMe($error, "debug");
break;
default:
$this->logMe($error, "warn");
}
}
private function shutdownHandler() //will be called when php script ends.
{
$lasterror = error_get_last();
echo "Level: " . $lasterror;
switch ($lasterror['type'])
{
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
case E_RECOVERABLE_ERROR:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_PARSE:
$error = "[SHUTDOWN] lvl:" . $lasterror['type'] . " | msg:" . $lasterror['message'] . " | file:" . $lasterror['file'] . " | ln:" . $lasterror['line'];
$this->logMe($error, "fatal");
}
}
private function logMe($error, $errlvl)
{
echo 'Error No: ' . $error . ' <BR> Error Level: ' .$errlvl;
}
}
...
<?php
// Index.php
include "Logs.php"
new MyLogs();
echo $b; //this should generate a notice error since $b does not exits...
但是,如果我不使用课程而只使用功能,它们可以正常工作......有人可以告诉我什么是错的吗?
由于
答案 0 :(得分:9)
您应该正确设置错误设置。例如
ini_set('error_reporting', -1);
ini_set('display_errors', 1);
在此之后您会发现错误:您的shutdownHandler
和errorHandler
必须公开。