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