Yii2 日志控制台命令输出

Yii2 log console command output

我想知道如何将 Yii2 控制台命令的输出保存到文件中?或者,如果命令作为 cronjob 运行,我如何记录输出以便稍后阅读?

谢谢。

解决方案

正如 Beowulfenator 所指出的,我使用了 Yii 的 Logger 特性。 因此,在我的配置文件中,我为 trace 级别定义了一个新的 FileTarget

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

在我的控制台控制器中,我重写了 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;
}

最好的方法是使用 stream redirection。你基本上写这样的东西来创建一个新的日志文件或每次你的脚本运行时覆盖现有的日志文件:

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

...或类似这样的东西附加到现有日志文件,累积数据:

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

这种方法并非特定于 yii,您可以在任何地方重定向几乎任何内容的输出。

您可能不想将命令的 所有 输出记录到文件中。那么你应该考虑使用 Yii2 的 logging feature 和一个文件目标。您定义将保存日志的文件。然后,如果某些内容需要进入日志,您可以使用 Yii::trace() 或其他适当的命令进行,如果消息只需要在屏幕上显示,您可以 echo 它。