【发布时间】:2020-03-23 01:03:20
【问题描述】:
我正在构建一个 MVC PHP 框架。我正在处理错误记录。我正在测试一个系统以显示和记录(在 .txt 文件中)由 try、catch 块引发的错误。由于篇幅短,我把index.php全都收录了:
<?php
// *** SETUP THE DOCUMENT ***
// Declare strict_types.
declare(strict_types = 1);
// Include the autoload file.
require_once "classes/autoload.php";
// Create a new config variable to allow us to call the config file from anywhere.
new Config();
// Setup error reporting according to the config.
error_reporting(Config::$config['defaults']['errReporting']);
ini_set("display_errors", Config::$config['defaults']['ini_setErrors']);
// Errors::showCatch("Test");
try {
$test = new QueryExamples();
$test->getTexts();
} catch (Error $e) {
Errors::showCatch($e);
}
unset($test);
我已经安装了自动加载器。如果有人想要,我将包含该代码。下一位是名为 errors.php 的文件,由 try、catch 调用,并且根据框架的配置文件的设置方式,在屏幕上显示消息和/或将其发送到日志文件:
class Errors{
static function showCatch($errMessage){
// If manual errors are turned on in the config file.
if(Config::$config['defaults']['manErrors'] == 1){
// Show the error message.
echo "<br />{$errMessage}<br />";
}
// Log the error.
Logs::logManError($errMessage);
die();
}
}
在文件中记录的方式和位置由另一个文档中的另一个静态函数处理:
class Logs{
static function logManError($errMessage) {
// If custom error logging is turned on in the config file:
if (Config::$config['defaults']['customErrorsLogging'] == 1) {
// Get the file path from the config file.
$manErrors_file = Config::$config['paths']['customErrors'];
// Format the error message.
$logTxt = "New Custom Error - [".date("d/m/Y - H:i:s")."]\n".$errMessage."\n\n";
file_put_contents($manErrors_file, $logTxt, FILE_APPEND);
}
}
}
日志文件中的输出:
New Custom Error - [23/03/2020 - 01:50:17]
Error: (Error message)
New Custom Error - [23/03/2020 - 01:50:17]
Error: (Error message)
我更改了错误消息以尝试查找错误被调用的位置:
// Format the error message.
// $logTxt = "New Custom Error - [".date("d/m/Y - H:i:s")."]\n".$errMessage."\n\n";
$logTxt = debug_backtrace()["0"]['file']." ".debug_backtrace()['0']['line']."\n".debug_backtrace()['1']['file']." ".debug_backtrace()['1']['line']."\n\n";
日志文件中的输出:
F:\xampp\htdocs\FRED 0.0.0\classes\errors.php 21
F:\xampp\htdocs\FRED 0.0.0\index.php 22
F:\xampp\htdocs\FRED 0.0.0\classes\errors.php 21
F:\xampp\htdocs\FRED 0.0.0\index.php 22
errors.php:21 是我调用 Logs:logManError() 静态函数的位置,index.php:22 是我在 try、catch 块中调用 Errors:showCatch() 函数的位置。
我还尝试向index.php 添加一个全局变量来检查showCatch() 函数被调用了多少次:
(index.php)
$GLOBALS['i'] = 0;
(errors.php)
$GLOBALS['i'] += 1;
// Log the error.
Logs::logManError($errMessage."<br />".$GLOBALS['i']);
die();
输出:
New Custom Error - [23/03/2020 - 01:50:17]
Error: (Error message)
1
New Custom Error - [23/03/2020 - 01:50:17]
Error: (Error message)
1
【问题讨论】:
-
你能包括你的 try/catch 块的周围源吗?可能 try/catch 块被执行了两次?换句话说,这个 try/catch 块在您的源代码中的什么位置?由于您显示的源代码似乎正确,因此需要该部分的一些上下文来进一步调试。
-
我尝试更改调用 showCatch 函数的方式。您可以看到注释掉的行。当我注释掉 try catch 块并取消注释 Errors::showCatch("Test"); 时,它仍然会产生相同的结果;线。 tryCatch 块中的错误是 getTexts() 方法不存在。
-
你在使用调试器吗?如果是这样,您可以在写入日志的位置设置断点,并查看堆栈跟踪。如果断点被命中两次,你会看到第二个是从哪里来的。
标签: php error-logging