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                 $request = Yii::$app->getRequest();
19                 $ip = $request instanceof Request ? $request->getUserIP() : ‘-‘;
20                 $controller = Yii::$app->controller->id;
21                 $action = Yii::$app->controller->action->id;
22                 return "[$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()](http://www.php.net/manual/en/function.rename.php)
18      * function does not work with files that are opened by some process is described in a
19      * [comment by Martin Pelletier](http://www.php.net/manual/en/function.rename.php#102274) 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 = $this->logFile;
31         for ($i = $this->maxLogFiles; $i >= 0; --$i) {
32             // $i == 0 is the original log file
33             $rotateFile = $file . ($i === 0 ? ‘‘ : ‘.‘ . $i);
34             if (is_file($rotateFile)) {
35                 // suppress errors because it‘s possible multiple processes enter into this section
36                 if ($i === $this->maxLogFiles) {
37                     @unlink($rotateFile);
38                 } else {
39                     if ($this->rotateByCopy) {
40                         @copy($rotateFile, $file . ‘.‘ . ($i + 1));
41                         if ($fp = @fopen($rotateFile, ‘a‘)) {
42                             @ftruncate($fp, 0);
43                             @fclose($fp);
44                         }
45                         if ($this->fileMode !== null) {
46                             @chmod($file . ‘.‘ . ($i + 1), $this->fileMode);
47                         }
48                     } else {
49                         // linux下用rename方式
50                         @rename($rotateFile, $file . ‘.‘ . ($i + 1));
51                     }
52                 }
53             }
54         }
55     }
56 }

  5.日志前缀

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

 1 public function getMessagePrefix($message)
 2 {
 3     if ($this->prefix !== null) {
 4         return call_user_func($this->prefix, $message);
 5     }
 6
 7     if (Yii::$app === null) {
 8         return ‘‘;
 9     }
10
11     $request = Yii::$app->getRequest();
12     $ip = $request instanceof Request ? $request->getUserIP() : ‘-‘;
13
14     /* @var $user \yii\web\User */
15     $user = Yii::$app->has(‘user‘, true) ? Yii::$app->get(‘user‘) : null;
16     if ($user && ($identity = $user->getIdentity(false))) {
17         $userID = $identity->getId();
18     } else {
19         $userID = ‘-‘;
20     }
21
22     /* @var $session \yii\web\Session */
23     $session = Yii::$app->has(‘session‘, true) ? Yii::$app->get(‘session‘) : null;
24     $sessionID = $session && $session->getIsActive() ? $session->getId() : ‘-‘;
25
26     return "[$ip][$userID][$sessionID]";
27 }

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

时间: 2024-08-07 00:03:19

Yii2 日志处理的相关文章

我 && yii2(日志埋点,邮件提醒)

今天试着把yii2 的日志,如果发送邮件的形式实现,具体实现如下 1.环境介绍 lnmp php5.6, mysql5.5, lnmp1.2 yii2-advanced 2.配置文件的编写 在frontend/config/main.php 添加mailer 和 log 的配置 'mailer' => require_once '../config/mail.php', 'log' => require_once '../config/log.php', mailer的配置如下(fronten

yii2 日志功能使用记录

日志配置(在@config/web.php中): 'log' => [     'traceLevel' => YII_DEBUG ? 3 : 0,     'targets' => [         [             'class' => 'yii\log\FileTarget',             'levels' => ['error', 'warning'],         ],         [            //日志记录方式     

YII2 日志

YII 提供的日志写入方法: Yii::getLogger()->log($message, $level, $category = 'application') Yii::trace($message, $category = 'application'); Yii::error($message, $category = 'application'); Yii::warning($message, $category = 'application'); Yii::info($message,

Yii 2.0进阶版 高级组件 ES/Redis/ Sentry 优化京东平台

第1章 课程简介本章内容会给大家通览本门课程的所有知识点. 第2章 Yii2框架的Assets前端资源发布的使用本章我们会详细学习Assets组件的使用,使用Nav插件和Breadcrumbs插件进行导航的加载,轻松安装加载第三方组件JSTree完成无限分类的树形展示,如何设置前端资源文件按需加载和使用压缩后的资源文件加速前端页面的加载 第3章 Yii2框架的用户认证体系本章对Web系统的用户认证体系进行重构,我们将使用Yii2框架的用户认证User组件重新设计用户的登录和退出操作,并使用过滤器

Yii2.0 自定义日志类

Yii2.0的日志功能虽然说已经很强大,但有时候,我们需要在程序运行的关键地方加入日志.这样使用Yii2.0系统提供日志功能,就有一些不太习惯.(ps:也许是我的Yii2.0使用的不熟悉) 这里我在extensions下建了一个utils目录并建了一个名为FileLog的php文件继承yii\log\FileTarget类.不多了,直接上代码,大家一看就明白了. <?php namespace app\extensions\utils; use Yii; use yii\helpers\File

Yii2 将日志记录到数据库中

Yii2默认日志记录到文件中,通过配置log组件来重新将日志保存到数据库中 打开config目录下console.php文件,修改log配置 'log' => [ 'targets' => [ [ 'class' => 'yii\log\DbTarget', 'levels' => ['error', 'warning'], ], ], ], 打开cmd 命令行,进入Yii根目录,开始创建数据库 yii migrate [email protected]/log/migration

Yii2 捕获错误日志

在技术开发中,捕获程序框架错误,是非常必要的一件事情,我们公司使用Yii2框架,简单说下Yii2的错误捕获处理 Yii2 web应用 1 配置如下 其中errorHandler就是错误处理配置,执行ErrorController的actionError 'components' => [     "urlManager" => require (__DIR__ . '/router.php'),     'errorHandler' => [         'err

Yii2如何添加sql日志记录的配置信息

在使用Yii2框架的时候,常常会出现没有sql日志记录的问题.在代码里一句一句的打印sql语句也不现实.所以就要用文件记录起来. 在 config/web.php 里面的 log配置中增加如下配置 [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning','info'], 'logVars'=>[], //表示以yii\db\或者app\models\开头的分类都会写入这个文件 'categories'=>

YII2 自定义日志路径

YII 提供的日志写入方法: 1.Yii::getLogger()->log($message, $level, $category = 'application') 2.Yii::trace($message, $category = 'application'); 3.Yii::error($message, $category = 'application');4.Yii::warning($message, $category = 'application');5.Yii::info($