Yii2 日志处理

时间:2023-01-21 04:16:29

  最近开发一个新的PHP项目,终于脱离了某框架的魔爪(之前被折磨的不轻),选用了江湖中如雷贯耳的Yii2框架。每个项目代码的运行,日志是必不可少的,在开发中踩了一遍Yii2日志管理的坑,看过很多网上对Yii2日志的配置介绍,今天总结一下Yii2对日志的处理分享给大家。

  1.首先看一下log配置:

 return [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [ //可以配置多个log
[
'class' => 'yii\log\FileTarget', //Yii2处理日志的类
'levels' => ['error', 'warning', 'info'], //设置日志记录的级别
'categories' => ['user'], //自定义日志分类
'maxFileSize' => 1024 * 20, //设置文件大小,以k为单位
'logFile' => '@runtime/../logs/user'.date('Ymd'), //自定义文件路径 (一般项目的日志会打到服务器的其他路径,需要修改相应目录的权限哦~)
'logVars' => ['_POST'], //捕获请求参数
'fileMode' => 0775, //设置日志文件权限
'maxLogFiles' => 100, //同个文件名最大数量
'rotateByCopy' => false, //是否以复制的方式rotate
'prefix' => function() { //日志格式自定义 回调方法
if (Yii::$app === null) {
return '';
}
$request = Yii::$app->getRequest();
$ip = $request instanceof Request ? $request->getUserIP() : '-';
$controller = Yii::$app->controller->id;
$action = Yii::$app->controller->action->id;
return "[$ip][$controller-$action]";
},
],
];

  2.日志记录

    Yii::trace():记录一条消息去跟踪一段代码是怎样运行的。这主要在开发的时候使用。 
    Yii::info():记录一条消息来传达一些有用的信息。 
    Yii::warning():记录一个警告消息用来指示一些已经发生的意外。 
    Yii::error():记录一个致命的错误,这个错误应该尽快被检查。

    eg: Yii::info('the log content', 'user');

      第二个参数可以是自定义的日志分类,对应配置文件中categories字段。

  3.日志组件调用

    log配置通过web.php(基础模板web.php 高级模板main.php)以component方式加载到应用对象Yii::$app中。

  4.日志切分

    ./vendor/yiisoft/yii2/log/FileTarget.php

 class FileTarget extends Target
{
public $logFile;
//rotation开关 如果开启,当日志文件大于maxFileSize设定的文件大小之后,就会自动切分日志
public $enableRotation = true;
public $maxFileSize = 10240; // in KB
//同一个文件名可以切分多少个文件
public $maxLogFiles = 5;
public $fileMode; //日志文件权限
public $dirMode = 0775;
/**
* @var bool Whether to rotate log files by copy and truncate in contrast to rotation by
* renaming files. Defaults to `true` to be more compatible with log tailers and is windows
* systems which do not play well with rename on open files. Rotation by renaming however is
* a bit faster.
*
* The problem with windows systems where the [rename()](http://www.php.net/manual/en/function.rename.php)
* function does not work with files that are opened by some process is described in a
* [comment by Martin Pelletier](http://www.php.net/manual/en/function.rename.php#102274) in
* the PHP documentation. By setting rotateByCopy to `true` you can work
* around this problem.
*/
public $rotateByCopy = true; /**
* Rotates log files.
*/
protected function rotateFiles()
{
$file = $this->logFile;
for ($i = $this->maxLogFiles; $i >= 0; --$i) {
// $i == 0 is the original log file
$rotateFile = $file . ($i === 0 ? '' : '.' . $i);
if (is_file($rotateFile)) {
// suppress errors because it's possible multiple processes enter into this section
if ($i === $this->maxLogFiles) {
@unlink($rotateFile);
} else {
if ($this->rotateByCopy) {
@copy($rotateFile, $file . '.' . ($i + 1));
if ($fp = @fopen($rotateFile, 'a')) {
@ftruncate($fp, 0);
@fclose($fp);
}
if ($this->fileMode !== null) {
@chmod($file . '.' . ($i + 1), $this->fileMode);
}
} else {
// linux下用rename方式
@rename($rotateFile, $file . '.' . ($i + 1));
}
}
}
}
}
}

  5.日志前缀

    prefix:如果没有配置,默认调用./vendor/yiisoft/yii2/log/Target.php

 public function getMessagePrefix($message)
{
if ($this->prefix !== null) {
return call_user_func($this->prefix, $message);
} if (Yii::$app === null) {
return '';
} $request = Yii::$app->getRequest();
$ip = $request instanceof Request ? $request->getUserIP() : '-'; /* @var $user \yii\web\User */
$user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
if ($user && ($identity = $user->getIdentity(false))) {
$userID = $identity->getId();
} else {
$userID = '-';
} /* @var $session \yii\web\Session */
$session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
$sessionID = $session && $session->getIsActive() ? $session->getId() : '-'; return "[$ip][$userID][$sessionID]";
}

    如果想要自定义日志格式前缀,可以配置回调函数(note:如果在回调中使用了特定的类需要在文件开头用“use”关键词 引入该类)

Yii2 日志处理