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

问题描述 投票:6回答:2

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

但是命令不会以这种方式完成。 :(

php symfony stream command
2个回答
11
投票

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


0
投票

我需要做同样的事情,在我的情况下,我想通过电子邮件将控制台输出进行调试和审计,然后通过电子邮件发送给电子邮件,因此,我制作了一个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警告等。

© www.soinside.com 2019 - 2024. All rights reserved.