【问题标题】:PHP: Redirect output of a bash command into default loggerPHP:将 bash 命令的输出重定向到默认记录器
【发布时间】:2016-04-22 17:38:42
【问题描述】:

我有一个类在我的控制台中执行命令。此类使用从 @logger.handler 定义的 LoggerInterface 定义。

我想在我的 bash 中执行命令但是:

  • 我不想在默认流中显示结果
  • 我想将结果放入默认日志文件(由 $logger 定义),例如app/logs/application.log

这个类的主要方法是这样的:

$command = $command . " > 2>&1";
$returnVal = null;
$output = [];
exec($command, $output, $returnVal);
$this->logger->debug($output);

我添加了> 2>&1 以在当前流中不显示任何内容,因为我不知道如何从 $output 中获取app/log/application.log...

问题是我的 app/config/application.log 中没有任何内容!

你知道我错过了什么吗?

【问题讨论】:

  • 你试过$command = $command . " > \"app/config/application.log\""; ?
  • @Tarek 我很确定它会起作用,但我不想设置这个路径硬编码,因为当你在开发模式下运行你的应用程序时它可能会有所不同,或者从依赖注入中覆盖.
  • 然后$command = $command . " > \"" . $logger . "\"" ?
  • @Tarek 我不会自己定义$dir。我想从应用程序中获取它,但我不知道如何获取它。
  • 你说你有存储在$logger的值

标签: php bash logging stream exec


【解决方案1】:

由于> 2>&1,您没有在输出中捕获任何内容

//$command = $command . " > 2>&1";
$returnVal = null;
$output = [];
exec($command, $output, $returnVal);
for ($i=0;$i<count($output);$i++)
    $this->logger->debug($output[$i]);

如果调试器为每个时间戳创建了多个时间戳,但它不是所需的输出,则使用此:

$returnVal = null;
$output = [];
exec($command, $output, $returnVal);
$result=""
for ($i=0;$i<count($output);$i++)
    $result.=$output[i]."\n";
$this->logger->debug($result);

【讨论】:

  • 此解决方案有效,但仅返回 exec 命令的最后一行...与预期不符:(
  • 此解决方案在我运行时会在控制台中显示所有结果。
  • 只需将它附加到调试器中,我是否必须为你编辑所有内容:P
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 2017-11-26
相关资源
最近更新 更多