teh*_*tro 6 console logging yii2
我想知道如何将Yii2控制台命令的输出保存到文件中?或者我如何记录输出,以便稍后可以读取,例如,如果命令以cronjob的形式运行?
谢谢.
解
正如Beowulfenator所指出的,我使用了Yii的Logger功能.所以,在我的配置文件中,我FileTarget为该trace级别定义了一个新的.
// config/console.php
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['trace'],
'logVars' => [],
'logFile' => '@runtime/logs/commands.log'
]
],
],
Run Code Online (Sandbox Code Playgroud)
在我的控制台控制器中,我重写了stdout这样的方法:
/* 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;
}
Run Code Online (Sandbox Code Playgroud)
最好的方法是使用流重定向。您基本上会编写类似这样的内容来创建新的日志文件或在每次脚本运行时覆盖现有的日志文件:
yii example-controller/example-action > example.log
Run Code Online (Sandbox Code Playgroud)
...或类似的东西附加到现有日志文件,累积数据:
yii example-controller/example-action >> example.log
Run Code Online (Sandbox Code Playgroud)
这种方法并不是 yii 特有的,您可以在任何地方重定向几乎任何内容的输出。
您可能不想将所有命令的输出记录到文件中。那么你应该考虑使用 Yii2 的日志记录功能和文件目标。您定义保存日志的文件。然后,如果某些内容需要进入日志,您可以使用Yii::trace()或其他适当的命令来执行此操作,如果该消息只需要显示在屏幕上,则可以使用echo它。
| 归档时间: |
|
| 查看次数: |
9202 次 |
| 最近记录: |