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;
}
Creating a new log target class is very simple. You mainly need to implement the yii\log\Target::export() method sending the content of the yii\log\Target::$messages array to a designated medium. You may call the yii\log\Target::formatMessage() method to format each message.
If you are using default Yii main. php file then all the logs go to your protected/runtime/application. log file. It will include standard Yii logs as well as you own Yii::log() calls too.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With