获取Symfony命令的输出并将其保存到文件中


Get output of a Symfony command and save it to a file

我正在使用Symfony2.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);

但命令并没有以这种方式结束。:(

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

我也需要同样的东西,在我的情况下,我想通过电子邮件将调试和审计的控制台输出发送到电子邮件,所以我制作了一个非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警告等。

很抱歉再次提起此事。我也处于类似的情况,如果您浏览Symfony版本(2.7以后)的代码,就已经有了解决方案。

您可以很容易地将其适应您的特定问题:

    // 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();

这应该能很好地解决问题。