Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using Symfony 2.0.

I have created a command in Symfony and I want to take its output and write it to a file.

All I want is to take everything that is written on the standard output (on the console) and to have it in a variable. By all I mean things echoed in the command, exceptions catched in other files, called by the command and so on. I want the output both on the screen and in a variable (in order to write the content of the variable in a file). I will do the writing in the file in the end of the execute() method of the command.

Something like this:

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

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

And in the file I want to have:

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

Can you please help me?

I tried something like this:

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

but the command doesn't finish in that way. :(

like image 631
Faery Avatar asked Oct 07 '14 08:10

Faery


1 Answers

You could just forward the command output using standard shell methods with php app/console your:command > output.log. Or, if this is not an option, you could introduce a wrapper for the OutputInterface that would write to a stream and then forward calls to the wrapped output.

like image 69
kix Avatar answered Sep 25 '22 08:09

kix