Yii2 日志处理
最近开发一个新的PHP项目,终于脱离了某框架的魔爪(之前被折磨的不轻),选用了江湖中如雷贯耳的Yii2框架。每个项目代码的运行,日志是必不可少的,在开发中踩了一遍Yii2日志管理的坑,看过很多网上对Yii2日志的配置介绍,今天总结一下Yii2对日志的处理分享给大家。
1.首先看一下log配置:
复制代码
1 return [
2 ‘traceLevel’ => YII_DEBUG ? 3 : 0,
3 ‘targets’ => [ //可以配置多个log
4 [
5 ‘class’ => ‘yii\log\FileTarget’, //Yii2处理日志的类
6 ‘levels’ => [‘error’, ‘warning’, ‘info’], //设置日志记录的级别
7 ‘categories’ => [‘user’], //自定义日志分类
8 ‘maxFileSize’ => 1024 * 20, //设置文件大小,以k为单位
9 ‘logFile’ => ‘@runtime/…/logs/user’.date(‘Ymd’), //自定义文件路径 (一般项目的日志会打到服务器的其他路径,需要修改相应目录的权限哦~)
10 ‘logVars’ => [’_POST’], //捕获请求参数
11 ‘fileMode’ => 0775, //设置日志文件权限
12 ‘maxLogFiles’ => 100, //同个文件名最大数量
13 ‘rotateByCopy’ => false, //是否以复制的方式rotate
14 ‘prefix’ => function() { //日志格式自定义 回调方法
15 if (Yii::$app === null) {
16 return ‘’;
17 }
18
r
e
q
u
e
s
t
=
Y
i
i
:
:
request = Yii::
request=Yii::app->getRequest();
19 $ip = $request instanceof Request ? $request->getUserIP() : ‘-’;
20
c
o
n
t
r
o
l
l
e
r
=
Y
i
i
:
:
controller = Yii::
controller=Yii::app->controller->id;
21
a
c
t
i
o
n
=
Y
i
i
:
:
action = Yii::
action=Yii::app->controller->action->id;
22 return “[
i
p
]
[
ip][
ip][controller-$action]”;
23 },
24 ],
25 ];
复制代码
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
复制代码
1 class FileTarget extends Target
2 {
3 public $logFile;
4 //rotation开关 如果开启,当日志文件大于maxFileSize设定的文件大小之后,就会自动切分日志
5 public $enableRotation = true;
6 public $maxFileSize = 10240; // in KB
7 //同一个文件名可以切分多少个文件
8 public $maxLogFiles = 5;
9 public $fileMode; //日志文件权限
10 public $dirMode = 0775;
11 /**
12 * @var bool Whether to rotate log files by copy and truncate in contrast to rotation by
13 * renaming files. Defaults to true
to be more compatible with log tailers and is windows
14 * systems which do not play well with rename on open files. Rotation by renaming however is
15 * a bit faster.
16 *
17 * The problem with windows systems where the rename()
18 * function does not work with files that are opened by some process is described in a
19 * comment by Martin Pelletier in
20 * the PHP documentation. By setting rotateByCopy to true
you can work
21 * around this problem.
22 /
23 public $rotateByCopy = true;
24
25 /*
26 * Rotates log files.
27 */
28 protected function rotateFiles()
29 {
30 $file =
t
h
i
s
−
>
l
o
g
F
i
l
e
;
31
f
o
r
(
this->logFile; 31 for (
this−>logFile;31for(i = $this->maxLogFiles;
i
>
=
0
;
−
−
i >= 0; --
i>=0;−−i) {
32 // $i == 0 is the original log file
33 $rotateFile =
f
i
l
e
.
(
file . (
file.(i === 0 ? ‘’ : ‘.’ .
i
)
;
34
i
f
(
i
s
f
i
l
e
(
i); 34 if (is_file(
i);34if(isfile(rotateFile)) {
35 // suppress errors because it’s possible multiple processes enter into this section
36 if ($i === KaTeX parse error: Expected '}', got 'EOF' at end of input: … @unlink(rotateFile);
38 } else {
39 if (KaTeX parse error: Expected '}', got 'EOF' at end of input: … @copy(rotateFile,
f
i
l
e
.
′
.
′
.
(
file . '.' . (
file.′.′.(i + 1));
41 if (
f
p
=
@
f
o
p
e
n
(
fp = @fopen(
fp=@fopen(rotateFile, ‘a’)) {
42 @ftruncate(
f
p
,
0
)
;
43
@
f
c
l
o
s
e
(
fp, 0); 43 @fclose(
fp,0);43@fclose(fp);
44 }
45 if (KaTeX parse error: Expected '}', got 'EOF' at end of input: … @chmod(file . ‘.’ . ($i + 1), KaTeX parse error: Expected 'EOF', got '}' at position 45: … }̲ 48 …rotateFile,
f
i
l
e
.
′
.
′
.
(
file . '.' . (
file.′.′.(i + 1));
51 }
52 }
53 }
54 }
55 }
56 }
复制代码
5.日志前缀
prefix:如果没有配置,默认调用./vendor/yiisoft/yii2/log/Target.php
复制代码
1 public function getMessagePrefix(KaTeX parse error: Expected '}', got 'EOF' at end of input: …2 { 3 if (this->prefix !== null) {
4 return call_user_func($this->prefix, KaTeX parse error: Expected 'EOF', got '}' at position 18: …ssage); 5 }̲ 6 7 if …app === null) {
8 return ‘’;
9 }
10
11
r
e
q
u
e
s
t
=
Y
i
i
:
:
request = Yii::
request=Yii::app->getRequest();
12 $ip = $request instanceof Request ? $request->getUserIP() : ‘-’;
13
14 /* @var $user \yii\web\User /
15
u
s
e
r
=
Y
i
i
:
:
user = Yii::
user=Yii::app->has(‘user’, true) ? Yii::
a
p
p
−
>
g
e
t
(
′
u
s
e
r
′
)
:
n
u
l
l
;
16
i
f
(
app->get('user') : null; 16 if (
app−>get(′user′):null;16if(user && ($identity = $user->getIdentity(false))) {
17 $userID = $identity->getId();
18 } else {
19 $userID = ‘-’;
20 }
21
22 / @var $session \yii\web\Session */
23
s
e
s
s
i
o
n
=
Y
i
i
:
:
session = Yii::
session=Yii::app->has(‘session’, true) ? Yii::$app->get(‘session’) : null;
24 $sessionID = $session && $session->getIsActive() ?
s
e
s
s
i
o
n
−
>
g
e
t
I
d
(
)
:
′
−
′
;
2526
r
e
t
u
r
n
"
[
session->getId() : '-'; 25 26 return "[
session−>getId():′−′;2526return"[ip][
u
s
e
r
I
D
]
[
userID][
userID][sessionID]";
27 }
复制代码
如果想要自定义日志格式前缀,可以配置回调函数(note:如果在回调中使用了特定的类需要在文件开头用“use”关键词 引入该类)