参考文章

http://www.yiichina.com/doc/guide/2.0/runtime-logging
http://yii2.techbrood.com/guide-logging.html
http://blog.csdn.net/gao_yu_long/article/details/51732181

配置日志

官网给出的例子如下:

return [
    // the "log" component must be loaded during bootstrapping time
    'bootstrap' => ['log'],
    
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\DbTarget',
                    'levels' => ['error', 'warning'],
                ],
                [
                    'class' => 'yii\log\EmailTarget',
                    'levels' => ['error'],
                    'categories' => ['yii\db\*'],
                    'message' => [
                       'from' => ['log@example.com'],
                       'to' => ['admin@example.com', 'developer@example.com'],
                       'subject' => 'Database errors at example.com',
                    ],
                ],
            ],
        ],
    ],
];

上面这段代码的意思为:

  1. 当有errorwarning级别错误,使用yii\log\DbTarget类记录日志。
  2. 当有error级别错误,并且分类属于yii\db\*,使用yii\log\EmailTarget类记录日志,并附带message参数。

http://yii2.techbrood.com 给出的例子如下:

[
    'components' => [
        'log' => [
            'targets' => [
                'file' => [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['trace', 'info'],
                    'categories' => ['yii\*'],
                ],
                'email' => [
                    'class' => 'yii\log\EmailTarget',
                    'levels' => ['error', 'warning'],
                    'message' => [
                        'to' => ['admin@example.com', 'developer@example.com'],
                        'subject' => 'New example.com log message',
                    ],
                ],
            ],
        ],
    ],
]

给每个日志目标设置名称,然后可以通过 yiilogLogger::targets 属性来引用

Yii::$app->log->targets['file']->enabled = false;

使用方法

预置的快捷使用方法:

Yii::trace() //用于开发调试时记录日志,需要把 YII_DEBUG 设置为 true.
Yii::error() //用于记录不可恢复的错误。
Yii::warning() //一些不影响应用程序执行的警告信息。
Yii::info() //一些系统事件记录如管理员操作提示。

以上方法的实现为:

public static function trace($message, $category = 'application')
{
    if (YII_DEBUG) {
        static::getLogger()->log($message, Logger::LEVEL_TRACE, $category);
    }
}

public static function error($message, $category = 'application')
{
    static::getLogger()->log($message, Logger::LEVEL_ERROR, $category);
}

public static function warning($message, $category = 'application')
{
    static::getLogger()->log($message, Logger::LEVEL_WARNING, $category);
}

public static function info($message, $category = 'application')
{
    static::getLogger()->log($message, Logger::LEVEL_INFO, $category);
}

预置的错误级别:
\vendor\yiisoft\yii2\log\Logger.php

const LEVEL_ERROR = 0x01;
const LEVEL_WARNING = 0x02;
const LEVEL_INFO = 0x04;
const LEVEL_TRACE = 0x08;
const LEVEL_PROFILE = 0x40;
const LEVEL_PROFILE_BEGIN = 0x50;
const LEVEL_PROFILE_END = 0x60;
最后修改:2021 年 01 月 12 日 08 : 03 PM
如果觉得我的文章对你有用,请随意赞赏