【问题标题】:Get output of a Symfony command and save it to a file获取 Symfony 命令的输出并将其保存到文件中
【发布时间】:2014-12-01 15:21:16
【问题描述】:

我正在使用 Symfony 2.0

我在 Symfony 中创建了一个命令,我想获取它的输出并将其写入文件。

我想要的只是把所有写在标准输出(在控制台上)的东西都放在一个变量中。我的意思是命令中回显的东西,在其他文件中捕获的异常,由命令调用等等。我想要屏幕和变量中的输出(以便将变量的内容写入文件中)。我将在命令的execute() 方法的末尾写入文件。

类似这样的:

protected function execute(InputInterface $input, OutputInterface $output)
{
    // some logic and calls to services and functions
    echo 'The operation was successful.';

    $this->writeLogToFile($file, $output???);
}

在我想要的文件中:

[Output from the calls to other services, if any]
The operation was successful.

你能帮帮我吗?

我尝试过这样的事情:

   $stream  = $output->getStream();
   $content = stream_get_contents($stream, 5);

但是命令并没有以这种方式完成。 :(

【问题讨论】:

  • 您可以编写自己的 Base Application 类并实现实现 OutputInterface 的编写器,您可以看到 here 的内容

标签: php symfony stream command


【解决方案1】:

很抱歉再次提出这个问题。 我也有类似的情况,如果你浏览 Symfony 版本(2.7 以上)的代码,已经有一个solution

你可以很容易地适应你的具体问题:

    // use Symfony\Component\Console\Output\BufferedOutput;
    // You can use NullOutput() if you don't need the output
    $output = new BufferedOutput();
    $application->run($input, $output);

    // return the output, don't use if you used NullOutput()
    $content = $output->fetch();

这应该可以很好地解决问题。

【讨论】:

    【解决方案2】:

    我需要同样的东西,在我的情况下,我想通过电子邮件将调试和审计的控制台输出发送到电子邮件,所以我制作了一个 PHP 类包装器,它存储行数据,然后传递给原始输出实例,这仅适用于 PHP 7+。

    protected function execute(InputInterface $input, OutputInterface $output) {
        $loggableOutput = new class {
            private $linesData;
            public $output;
    
            public function write($data) {
                $this->linesData .= $data;
                $this->output->write($data);
            }
    
            public function writeln($data) {
                $this->linesData .= $data . "\n";
                $this->output->writeln($data);
            }
    
            public function getLinesData() {
                return $this->linesData;
            }
        };
    
        $loggableOutput->output = $output;
    
        //do some work with output
    
        var_dump($loggableOutput->getLinesData());
    }
    

    请注意,这只会存储使用writewriteln OutputInterface 方法写入的数据,不会存储任何 PHP 警告等。

    【讨论】:

      【解决方案3】:

      您可以使用带有php app/console your:command > output.log 的标准shell 方法转发命令输出。或者,如果这不是一个选项,您可以为 OutputInterface 引入一个包装器,该包装器将写入流,然后将调用转发到包装后的输出。

      【讨论】:

      • 不幸的是,管道不起作用,因为 Symfony 输出内容的方式似乎不同......
      猜你喜欢
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 2022-01-17
      • 2013-01-17
      相关资源
      最近更新 更多