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;
}

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Thanks. Take a look at ob_start too. It might be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.