Я строю 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();
}
}
Как и где он регистрируется в файле, обрабатывается другой функцией stati c в другом документе:
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()
stati c, а index.php:22
- это место, где я вызвал функцию Errors:showCatch()
в блоке try, catch.
Я также попытался добавить глобальную переменную в index.php
для проверьте, сколько раз была вызвана функция showCatch()
:
(индекс. php)
$GLOBALS['i'] = 0;
(ошибки. 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