yiissy001 2016-01-13 16:15:03 5525次浏览 0条评论 2 1 0

原文链接: https://github.com/samdark/yii2-cookbook/blob/master/book/logging-problems-and-solutions.md

诚然,YII2中的日志功能是非常灵活的,基本的日志功能是非常简单的,但是如果你想定制自己的日志功能就要花一番精力了.以下是一些比较常用的定制化日志解决方案,希望能帮到大家.

仅将404错误写入文件,其他错误发email给管理员

404错误时非常常见但是并不重要的错误, 不值得专门将之email给管理员.所以只把这种错误写入一个文件就够了:

'components' => [
    'log' => [
        'targets' => [
            'file' => [
                'class' => 'yii\log\FileTarget',
                'categories' => ['yii\web\HttpException:404'],
                'levels' => ['error', 'warning'],
                'logFile' => '@runtime/logs/404.log',
            ],
            'email' => [
                'class' => 'yii\log\EmailTarget',
                'except' => ['yii\web\HttpException:404'],
                'levels' => ['error', 'warning'],
                'message' => ['from' => 'robot@example.com', 'to' => 'admin@example.com'],
            ],
        ],
    ],
],

当遇到未经处理的exception的时候YII会记录日志并且展现到前台或展现特定的错误页面.Exception message才是真正被记录的内容,记录策略是根据我们配置中指定的Exception类名全称来决定哪些该被记录(原文:Exception message is what actually to be written and the fully qualified exception class name is the category we can use to filter messages when configuring targets).yii\web\HttpException:404表示yii\web\HttpException类下代表HTTP状态码为404的Excetpion类,也就是yii\web\NotFoundHttpException(原文太啰嗦,自己总结了一下).以上写法中用categories表示引入策略,except表示排除策略.

即时写入日志

在默认设置下, YII会等到脚本运行完或者满1000条消息时才会记日志.在某些情况下你可能需要即时记录日志的功能,以下是设置:

'components' => [
    'log' => [
        'flushInterval' => 1, // <-- here
        'targets' => [
            'file' => [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
                'exportInterval' => 1, // <-- and here
            ],
        ],
    ]
]

将不同日志写入不同文件

通常一个项目有很多功能.有时候必须根据日志监控这些功能,如果所有日志都记录到一个文件中那么这个文件会变得很大且很难处理.最好的办法是将他们按功能写入不同的文件中.

例如你有两个功能:catalog和basket.我们要将两个功能的日志分别写入catalog.log和basket.log两个文件中.你需要在你配置文件的log项中新建两个categorie,如下:

'components' => [
    'log' => [
        'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'categories' => ['catalog'],
                    'logFile' => '@app/runtime/logs/catalog.log',
                ],
                [
                    'class' => 'yii\log\FileTarget',
                    'categories' => ['basket'],
                    'logFile' => '@app/runtime/logs/basket.log',
                ],
        ],
    ]
]

在功能代码中你就可以通过如下写法将两者的日志记录到两个log文件中:

\Yii::info('catalog info', 'catalog');
\Yii::error('basket error', 'basket');
\Yii::beginProfile('add to basket', 'basket');
\Yii::endProfile('add to basket', 'basket');
觉得很赞
    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册