yii2 动态配置日志(log)
如果我们在项目中不允许修改配置文件中的 log 组件,那么动态配置 log 就变得很重要了,下面我分享一下动态配置 log 的方法:
默认的日志格式是 {date}{ip}{userID}{sessionID}{level}{category}{text}{trace}
这种方式不会让默认的 app.log 失效。(推荐)
public function init()
{
parent::init();
\Yii::$app->log->targets[] = \Yii::createObject([
'class' => 'yii\log\FileTarget',
'exportInterval' => 1, //立即刷新日志
'levels' => ['info', 'error'], // only display info ,error
'categories' => ['custom'], //log category
'logFile' => Yii::getAlias('@app').DIRECTORY_SEPARATOR.'runtime'.DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.'logFileName.log', // filePath
'logVars' => ['_GET', '_POST'], //只记录_GET _POST的值
'maxFileSize' => 1024 * 2, // 日志文件大小
'maxLogFiles' => 10, // 日志个数
]);
}
这种方式,异常不能写入 app.log 。
public function init()
{
parent::init();
Yii::$app->log->targets[0]->levels = ['info', 'error', 'warning']; // only display info ,error and warning
Yii::$app->log->targets[0]->categories = ['categoryName']; // log category
Yii::$app->log->targets[0]->logFile = Yii::getAlias('@app').DIRECTORY_SEPARATOR.'runtime'.DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.'logFileName.log'; // filePath
Yii::$app->log->targets[0]->logVars = ['*']; // don't display GET,POST,SERVER,COOKIE,SESSION, if config this,display otherwise.
Yii::$app->log->targets[0]->maxFileSize = 1024 * 2; // maxFileSize=2M
Yii::$app->log->targets[0]->maxLogFiles = 20; // maxLogFiles = 20
...
}
`