如何在将日志文件记录到日志文件的同时在后台运行PHP脚本,而无需挂起网页?在记录错误时在后台执行PHP脚本
我知道我可以使用这个命令exec("php -f background.php >/dev/null 2>&1 &");
,但是这不会将错误输出到日志文件。
background.php在用户提交表单时在后台执行。
这是用户提交表单后运行脚本(这不是后台脚本):
# Execute the script in the background Linux style. Writes errors to a log file.
exec("php -f background.php 2>&1 &", $error_result);
# If $error_result is not empty, there was an error (2>&1).
if(!empty($error_result))
{
# If $error_result is an array, convert it to a string seperated by PHP End of Line.
if(is_array($error_result))
{
$error_result=implode(PHP_EOL, $error_result);
}
# Get the Logger Class.
require_once Utility::locateFile(MODULES.'Logger'.DS.'Logger.php');
# Create a new Logger object, and set the log file to use.
$logger_obj=new Logger('command_line.log');
# Write exec() output to log file.
$logger_obj->writeLogFile($error_result);
# Close log file.
$logger_obj->closeLogFile();
}
以上脚本的工作,但该页面挂起,直到后台脚本完成。
编辑:所以,我从答案和评论中收集有没有办法使用$error_result
参数和我的记录器类来做到这一点。
我将尝试在background.php中添加try
和catch
,看看我是否可以通过这种方式记录错误。
你是不是想从background.php运行background.php?尝试从另一个脚本启动后台脚本来检查日志是否真的有效。 –
它肯定不会输出错误,因为您正通过添加'2>&1将STDERR重定向到/ dev/null。只需将其更改为'2>/path/to/error.log'?你在问什么? – ArSeN
@AbhishekPatel背景。当用户提交表单时,PHP会在后台执行。记录工作,整个脚本的作品,除了页面挂起,直到后台脚本完成。我希望网页在脚本在后台运行时继续。 – Draven