Home  >  Article  >  Backend Development  >  Comprehensive interpretation of the logging function in PHP's Yii framework_php skills

Comprehensive interpretation of the logging function in PHP's Yii framework_php skills

WBOY
WBOYOriginal
2016-05-16 19:56:461230browse

Yii page level logging is enabled
Add the log section in Main.php,
The page log array is displayed below ( 'class'=>'CWebLogRoute', 'levels'=>'trace', //The level is trace 'categories'=>'system.db.*' //Only display information about the database Information, including database connection, database execution statement),
The complete list is as follows:

'log'=>array(
    'class'=>'CLogRouter',
    'routes'=>array(
      array(
        'class'=>'CFileLogRoute',
        'levels'=>'error, warning',

      ),
              // 下面显示页面日志 
              array( 
               'class'=>'CWebLogRoute', 
               'levels'=>'trace',  //级别为trace 
               'categories'=>'system.db.*' //只显示关于数据库信息,包括数据库连接,数据库执行语句 
              ), 
      // uncomment the following to show log messages on web pages
      /*
      array(
        'class'=>'CWebLogRoute',
      ),
      */
    ),
  ),


Extended the log component that comes with Yii2

 <&#63;php

/**
 * author   : forecho <caizhenghai@gmail.com>
 * createTime : 2015/12/22 18:13
 * description:
 */
namespace common\components;

use Yii;
use yii\helpers\FileHelper;

class FileTarget extends \yii\log\FileTarget
{
  /**
   * @var bool 是否启用日志前缀 (@app/runtime/logs/error/20151223_app.log)
   */
  public $enableDatePrefix = false;

  /**
   * @var bool 启用日志等级目录
   */
  public $enableCategoryDir = false;

  private $_logFilePath = '';

  public function init()
  {
    if ($this->logFile === null) {
      $this->logFile = Yii::$app->getRuntimePath() . '/logs/app.log';
    } else {
      $this->logFile = Yii::getAlias($this->logFile);
    }
    $this->_logFilePath = dirname($this->logFile);

    // 启用日志前缀
    if ($this->enableDatePrefix) {
      $filename = basename($this->logFile);
      $this->logFile = $this->_logFilePath . '/' . date('Ymd') . '_' . $filename;
    }

    if (!is_dir($this->_logFilePath)) {
      FileHelper::createDirectory($this->_logFilePath, $this->dirMode, true);
    }

    if ($this->maxLogFiles < 1) {
      $this->maxLogFiles = 1;
    }
    if ($this->maxFileSize < 1) {
      $this->maxFileSize = 1;
    }

  }
}

Use like this in the configuration file:

'components' => [
  'log' => [
    'traceLevel' => YII_DEBUG &#63; 3 : 0,
    'targets' => [
      /**
       * 错误级别日志:当某些需要立马解决的致命问题发生的时候,调用此方法记录相关信息。
       * 使用方法:Yii::error()
       */
      [
        'class' => 'common\components\FileTarget',
        // 日志等级
        'levels' => ['error'],
        // 被收集记录的额外数据
        'logVars' => ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION','_SERVER'],
        // 指定日志保存的文件名
        'logFile' => '@app/runtime/logs/error/app.log',
        // 是否开启日志 (@app/runtime/logs/error/20151223_app.log)
        'enableDatePrefix' => true,
        'maxFileSize' => 1024 * 1,
        'maxLogFiles' => 100,
      ],
      /**
       * 警告级别日志:当某些期望之外的事情发生的时候,使用该方法。
       * 使用方法:Yii::warning()
       */
      [
        'class' => 'common\components\FileTarget',
        // 日志等级
        'levels' => ['warning'],
        // 被收集记录的额外数据
        'logVars' => ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION','_SERVER'],
        // 指定日志保存的文件名
        'logFile' => '@app/runtime/logs/warning/app.log',
        // 是否开启日志 (@app/runtime/logs/warning/20151223_app.log)
        'enableDatePrefix' => true,
        'maxFileSize' => 1024 * 1,
        'maxLogFiles' => 100,
      ],
      /**
       * info 级别日志:在某些位置记录一些比较有用的信息的时候使用。
       * 使用方法:Yii::info()
       */
      [
        'class' => 'common\components\FileTarget',
        // 日志等级
        'levels' => ['info'],
        // 被收集记录的额外数据
        'logVars' => ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION','_SERVER'],
        // 指定日志保存的文件名
        'logFile' => '@app/runtime/logs/info/app.log',
        // 是否开启日志 (@app/runtime/logs/info/20151223_app.log)
        'enableDatePrefix' => true,
        'maxFileSize' => 1024 * 1,
        'maxLogFiles' => 100,
      ],
      /**
       * trace 级别日志:记录关于某段代码运行的相关消息。主要是用于开发环境。
       * 使用方法:Yii::trace()
       */
      [
        'class' => 'common\components\FileTarget',
        // 日志等级
        'levels' => ['trace'],
        // 被收集记录的额外数据
        'logVars' => ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION','_SERVER'],
        // 指定日志保存的文件名
        'logFile' => '@app/runtime/logs/trace/app.log',
        // 是否开启日志 (@app/runtime/logs/trace/20151223_app.log)
        'enableDatePrefix' => true,
        'maxFileSize' => 1024 * 1,
        'maxLogFiles' => 100,
      ],
    ],
  ],
],

Logic of yii log
Yii uses a hierarchical log processing mechanism, that is, the collection of logs is separated from the final processing of logs (such as display, saving to files, and saving to data).
The collection of log information is completed by CLogger (log recorder), and the distribution and processing of log information is distributed to processing objects (such as CFileLogRoute and logging directory inherited from CLogRoute) under the scheduling of CLogRouter (called log routing manager). class, called log processor). After repeatedly reading its source code, I was even more impressed by Yii's design ideas. Such layered processing makes it easy to flexibly expand.
Log information is divided into levels, such as ordinary info, profile, trace, warning, and error levels. You can set filtering conditions in the log routing, such as setting the levels attribute of CFileRoute to only process log information of the specified level.
If called in the program:

Yii::log($message,CLogger::LEVEL_ERROR,$category);

The corresponding process may be as follows:

  • Generate CLogger instance
  • If YII_DEBUG and YII_TRACE_LEVEL have been defined as valid values, and the log level is not profile, call traceback information will be generated and appended to the log information.
  • Call CLogger::log($msg,$level,$category) to collect logs. In fact, the logs are not written to the file at this time, but are only temporarily stored in the memory.

Question: When is the log written to the file?
After repeated tracking, I found that the processor CLogRouter::processLogs() is bound to the OnEndRequest event of the Application object in the init method of the CLogRouter class. At the same time, the event processor CLogRouter::collectLogs method is also bound to the onFlush event of Yii::$_logger, which is used to refresh the log and write it to the file in a timely manner when there are too many log messages in Yii::log(). The code is as follows:

/**
 * Initializes this application component.
 * This method is required by the IApplicationComponent interface.  
*/
 public function init(){ 
  parent::init(); 
  foreach($this->_routes as $name=>$route) { 
    $route=Yii::createComponent($route);  
    $route->init();  
    $this->_routes[$name]=$route; 
  } 
  Yii::getLogger()->attachEventHandler('onFlush',array($this,'collectLogs')); 
  Yii::app()->attachEventHandler('onEndRequest',array($this,'processLogs'));}

And defined in the CApplication::run() method:

 if($this->hasEventHandler('onEndRequest')) {
 $this->onEndRequest(new CEvent($this));
 }

At this point we can understand that CLogger (Yii::$_logger) only collects logs (records them into the content structure), and then at the end of the program, the $app object calls CLogRouter's processLogs to process the logs. Yii supports multiple routing of logs. For example, the same log can be written to a file, displayed on the page, or even sent via email at the same time, or even recorded to the database at the same time. This is determined by the log in the configuration file: Routes configuration is implemented by configuring multiple elements for log:routes to achieve multiple route distribution. The filtering and recording of log information are processed by the final log processor.
The tasks to be completed by the log processor mainly include the following points: Obtain all logs from CLogger and filter them (mainly levels and categories defined by log:routes:levels/categories)

First filter and refer to the logic in CFileLogRoute::collectLogs():

 $logs=$logger->getLogs($this->levels,$this->categories); //执行过滤,只得到期望信息

Log filtering has been completed, and then the final processing of the logs (such as writing to files, recording to databases, etc.)

 CFileLogRoute::processLogs($logs);

But there is a small bug in this function. It only determines whether the log directory is writable, and does not determine whether the log file itself is writable. CFileLogRoute implements a log rotation function (LogRoate) similar to Linux, and stipulates the log file Big and small, very thoughtful and perfect! I also want to learn from him and absorb his ideas!
Configuration in protected/config/main.php:

'preload'=>array('log'),
components => array(
       'log'=>array(
         'class'=>'CLogRouter',
         'routes'=>array(
          array(
            'class'=>'CFileLogRoute',
            'levels'=>'error, warning,trace',
          ),
         )
        )
       )

Defining the log component requires preloading (instantiation). Configure CLogRouter as the log routing manager, and set its log routing processor (routes attribute) and its configuration attributes. The definition of preload and log attributes must be applied to the CWebApplication object (please refer to the configure call in CApplication::__construct, configure is inherited from CModule). When preloadComponents() is executed in the constructor of CWebApplication, the log object (that is, an instance of CLogRouter) is created.
When creating and initializing a component, CModule::getComponent is actually called. In this call, YiiBase::createComponent is used to create the component object, and then the init of the component is called to initialize it.
Read the CLogRouter::init() process again. There are two key points here. One is to create a log routing processor (that is, determine the final processing method of the log: writing to a file, sending an email, etc.), and the other is to give the application The object binds the onEndRequest event handler CLogRouter::processLogs(). There is indeed relevant code in CApplication::run() for running the onEndRequest event handler:

 if($this->hasEventHandler('onEndRequest')) {
  $this->onEndRequest(new CEvent($this));
 }

也就是说,日志的最终处理(比如写入文件,系统日志,发送邮件)是发生在应用程序运行完毕之后的。Yii使用事件机制,巧妙地实现了事件与处理句柄的关联。
也就是说,当应用程序运行完毕,将执行CLogRouter::processLogs,对日志进行处理,。CLogRouter被称之为日志路由管理器。每个日志路由处理器从CLooger对象中取得相应的日志(使用过滤机制),作最终处理。
具体而言Yii的日志系统,分为以下几个层次:

日志发送者,即程序中调用Yii::log($msg, $level, $category),将日志发送给CLogger对象
CLogger对象负责将日志记录暂存于内存之中程序运行结束后,log组件(日志路由管理器CLogRoute)的processLogs方法被激活执行,由其逐个调用日志路由器,作日志的最后处理。

更为详细的大致过程如下:

  • CApplication::__construct()中调用preloadComponents, 这导致log组件(CLogRoute)被实例化,并被调用init方法初始化。
  • log组件(CLogRoute)的init方法中,其是初始化日志路由,并给CApplication对象onEndRequest事件绑定处理流程processLogs。给CLooger组件的onFlush事件绑定处理流程collectLogs。
  • 应用程序的其它部分通过调用Yii::log()向CLogger组件发送日志信息,CLogger组件将日志信息暂存到内存中。
  • CApplication执行完毕(run方法中),会激活onEndRequest事件,绑定的事件处理器processLogs被执行,日志被写入文件之中。 Yii的日志路由机制,给日志系统扩展带来了无限的灵活。并且其多道路由处理机制,可将同一份日志信息进行多种方式处理。

这里举出一个案例:发生error级别的数据库错误时,及时给相关维护人员发送电子邮件,并同时将这些日志记录到文件之中。规划思路,发送邮件和手机短信是两个不同的功能,Yii已经带了日志邮件发送组件(logging/CEmailLogRoute.php),但这个组件中却使用了php自带的mail函数,使用mail函数需要配置php.ini中的smtp主机,并且使用非验证发送方式,这种方式在目前的实际情况下已经完全不可使用。代替地我们需要使用带验证功能的smtp发送方式。在protected/components/目录下定义日志处理器类myEmailLogRoute,并让其继承自CEmailLogRoute,最主要的目的是重写CEmailLogRoute::sendEmail()方法  ,其中,SMTP的处理细节请自行完善(本文的重点是放在如何处理日志上,而不是发送邮件上)。
接下来,我们就可以定义日志路由处理,编辑protected/config/main.php, 在log组件的routes组件添加新的路由配置:

'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning,trace',
),
array(
'class' => 'myEmailLogRoute',
'levels' => 'error', #所有异常的错误级别均为error, 
'categories' => 'exception.CDbException', #数据库产生错误时,均会产生CDbException异常。
'host' => 'mail.163.com',
'port' => 25,
'user' => 'jeff_yu',
'password' => 'you password',
'timeout' => 30,
'emails' => 'jeff_yu@gmail.com', #日志接收人。
'sentFrom' => 'jeff_yu@gmail.com',
),

经过以上处理,即可使之实现我们的目的,当然你可以根据自己的需要进一步扩展之。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn