2016-01-28 59 views
1

如何在将日志文件记录到日志文件的同时在后台运行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中添加trycatch,看看我是否可以通过这种方式记录错误。

+0

你是不是想从background.php运行background.php?尝试从另一个脚本启动后台脚本来检查日志是否真的有效。 –

+0

它肯定不会输出错误,因为您正通过添加'2>&1将STDERR重定向到/ dev/null。只需将其更改为'2>/path/to/error.log'?你在问什么? – ArSeN

+0

@AbhishekPatel背景。当用户提交表单时,PHP会在后台执行。记录工作,整个脚本的作品,除了页面挂起,直到后台脚本完成。我希望网页在脚本在后台运行时继续。 – Draven

回答

2

仍然运行exec("php -f background.php >/dev/null 2>&1 &");

但在文件中加入:

ini_set("log_errors","1"); 
ini_set("error_log",'path/to/erroor.txt'); 

确保您有一个路径,如果没有该文件将在用户的家中创建,用户将取决于这是怎么运行(可能是PHP)。

1

如果你想输出错误流至外部的日志文件,你可以做这样的:

exec("php background.php 1>/dev/null 2>background.log &", $output, $error_code); 

在这种情况下,我们将stdout到/dev/null和STDERR到文件background.log,并在后台运行background.php因为最后的&。对于php,您不需要-f选项。

你实际上可以跳过$output$error_code。我将它们包含在这里,所以我可以解释$output将始终为空阵列,并且$error_code将始终为0.所有这些都意味着OS(Linux)在后台成功创建了另一个进程。

由于1)background.php是在后台运行,并exec命令将立即返回,和2)$output$error_code不会告诉你,如果出了问题,则需要通过检查background.log检查错误别处。

让我知道如果我的解释不是很清楚,我会尽力详细说明。