这个问题在这里已经有了答案:
How do I log errors and warnings into a file?
(7 个回答)
How to write to error log file in PHP [closed]
(4 个回答)
1年前关闭。
我想要一种在 PHP
中写入错误和警告的方法脚本或脚本的输出,例如 echo "Hello World";在文本文件中
我不认为error_log()
函数对我来说很有用,因为这个函数记录了我之前在代码中提到的错误。
我想要的是这样的
PHP 代码
<?php
echo "Your Name is ".$name; // $name here is not defined
?>
此脚本将给出以下错误Notice: Undefined variable: name in C:\wamp64\www\example.php on line 3
此错误将自动写入我的服务器中的 php_error.log,但我想将此错误写入单独的文本文件中。
最佳答案
您可以使用使用 set_error_handler
设置的自定义错误处理程序来执行此操作。功能
<?php
function handleError($errorNumber, $errorString, $errorFile, $errorLine, array $errContext)
{
// Path to log file
$logFilePath = 'errors.log';
// Do we want to prevent the default PHP error handler from executing?
$allowDefaultLogging = true;
// error was suppressed with the @-operator do not log and cancel the default error handler
if (0 === error_reporting())
{
return false;
}
// Build log message string from error components
$message = $errorFile . ':' . $errorLine . ' errno ' . $errorNumber . ' ' . $errorString . PHP_EOL;
// Open the file for writing, append, create file if it does not exist
$logHandle = fopen($logFilePath, 'a+');
// Write the error message
fwrite($logHandle, $message);
// Close the file handle
fclose($logHandle);
// Tell PHP whether or not to handle the error with the default handler
return $allowDefaultLogging;
}
// Tell PHP we want errors to go to our custom handler
set_error_handler('handleError');
echo "Your Name is " . $name . PHP_EOL; // $name here is not defined
关于php - 将 PHP 脚本输出写入 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63711343/