6

I was wondering how can I save the output of an Yii2 console command to a file? Or how can I log the output so I can read it later, if the command runs as a cronjob for example?

Thanks.

SOLUTION

As pointed out by Beowulfenator, I used Yii's Logger feature. So, in my config file, I defined a new FileTarget for the trace level.

  // config/console.php
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['trace'],
                    'logVars' => [],
                    'logFile' => '@runtime/logs/commands.log'
                ]
            ],
        ],

In my console controller, I overridden the stdout method like this:

/* A public variable to catch all the output */
public $output;

/* Example of action outputting something to the console */
public function actionWhatever()
{
     $this->stdout("whatever");
}

/* Overriding stdout, first calling the parent impl which will output to the screen, and then storing the string */
public function stdout($string)
{
    parent::stdout($string);
    $this->output = $this->output.$string."\n";
}

/* In the afterAction hook, I log the output */
public function afterAction($action, $result)
{
    $result = parent::afterAction($action, $result);
    Yii::trace($this->output, 'categoryName');
    return $result;
}
tehmaestro
  • 1,010
  • 2
  • 11
  • 21

1 Answers1

4

The best way to do that is to use stream redirection. You basically write something like this to create a new log file or overwrite existing log file every time your script runs:

yii example-controller/example-action > example.log

...or something like this to append to an existing log file, accumulating the data:

yii example-controller/example-action >> example.log

This approach is not specific to yii, you can redirect output of pretty much anything anywhere.

There is a chance you don't want to log all of your command's output to a file. Then you should consider using Yii2's logging feature with a file target. You define the file that will hold your log. Then if something needs to go into log, you do so with Yii::trace() or another appropriate command, and if the message only needs to be shown on the screen, you echo it.

Beowulfenator
  • 2,262
  • 16
  • 26
  • Hi, this pointed me to the solution, so I will be accepting it as the answer. The way I did this is described in my original post. Thanks. – tehmaestro Sep 06 '15 at 07:47
  • Thanks. Take a look at [ob_start](http://php.net/manual/en/function.ob-start.php) too. It might be useful. – Beowulfenator Sep 06 '15 at 11:47