A comprehensive interpretation of the log function in the YII framework of PHP _php tips

Source: Internet
Author: User
Tags yii

Yii page-level log Open
in main.php, the log segment is added,
The following shows the page log array (' class ' => ' Cweblogroute ', ' Levels ' => ' trace ',//level for trace ' categories ' => ' system.db.* '/ Displays only information about the database, including database connections, database execution statements,
Complete as follows:

' Log ' =>array ('
    class ' => ' Clogrouter ', '
    routes ' =>array (
      Array (
        ' class ' => ') Cfilelogroute ',
        ' Levels ' => ' Error, warning ',

      ),
              //below Display page log 
              array ( 
               ' class ' => ') Cweblogroute ', 
               ' Levels ' => ' trace ',  //level for trace 
               ' categories ' => ' system.db.* '//Show only information about the database, Including database connections, database execution statements 
              ), 
      //Uncomment the following to show log messages on Web pages
      /* Array (
        ' Class ' => ' Cweblogroute ',), (*),
  ),


extended YII2 with its own log component

 <?php/** * Author:forecho <caizhenghai@gmail.com> * CREATETIME:2015/12/22 18:13 * Description:/n

Amespace common\components;
Use Yii;

Use Yii\helpers\filehelper;
   Class Filetarget extends \yii\log\filetarget {/** * @var bool Enable the log prefix (@app/runtime/logs/error/20151223_app.log)

  * * Public $enableDatePrefix = false;

  /** * @var bool Enable log level directory */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);
      Enables the log prefix 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;

 }

  }
}

The

uses this in a configuration file:

' Components ' => [' Log ' => [' TraceLevel ' => yii_debug] 3:0, ' targets ' => [/** * wrong
       Error level log: Call this method to log related information when a fatal problem that needs to be resolved immediately occurs. * How to use: Yii::error ()/[' Class ' => ' Common\components\filetarget ',//log rank ' level S ' => [' ERROR '],//collection of additional data recorded ' Logvars ' => [' _get ', ' _post ', ' _files ', ' _cookie ', ' _session ', ' _serv ' ER ',///specify log saved filename ' logFile ' => ' @app/runtime/logs/error/app.log ',//open log (@app/runtime/log S/error/20151223_app.log) ' Enabledateprefix ' => true, ' maxfilesize ' => 1024 * 1, ' maxlogfile
       S ' => 100,],/** * Warning Level log: Use this method when something outside of the expectation occurs. * Use method: Yii::warning ()/[' Class ' => ' Common\components\filetarget ',//log level ' Lev Els ' => [' warning '],//collection of additional data recorded ' Logvars ' => [' _get ', ' _post ', ' _files ', ' _cookie ', ' _session ', ' _ SERVER '],//Specifies the file name of the log save ' logFile ' => ' @app/runtime/logs/warning/app.log ',//whether to open the log (@app/runtime/logs/warning/20151 
      223_app.log) ' Enabledateprefix ' => true, ' maxfilesize ' => 1024 * 1, ' maxlogfiles ' => 100,
       ],/** * Info level log: Use when recording some of the more useful information in certain locations. * Use method: Yii::info ()/[' Class ' => ' Common\components\filetarget ',//log level ' levels ' => [' info '],//collection of additional data recorded ' Logvars ' => [' _get ', ' _post ', ' _files ', ' _cookie ', ' _session ', ' _server ' '],///specify log saved filename ' logFile ' => ' @app/runtime/logs/info/app.log ',//whether to open log (@app/runtime/logs/i Nfo/20151223_app.log) ' Enabledateprefix ' => true, ' maxfilesize ' => 1024 * 1, ' maxlogfiles ' = >,],/** * Trace level log: Records related messages about a piece of code running.
       Mainly for the development environment.
        * Use method: Yii::trace () * * [' class ' => ' Common\components\filetarget ',//log level' Levels ' => [' Trace '],//collected additional data recorded ' Logvars ' => [' _get ', ' _post ', ' _files ', ' _cookie ', ' _session ', ' _server '],//specify log saved filename ' logFile ' => ' @app/runtime/logs/trace/app.log ',//open log (@app/runti Me/logs/trace/20151223_app.log) ' Enabledateprefix ' => true, ' maxfilesize ' => 1024 * 1, ' MaxL

 Ogfiles ' => 100,],],,],

The logic of the Yii log
Yii uses a hierarchy of log processing mechanisms, that is, the collection of logs and the final processing of the log (such as display, save to file, save to the number of data) is separate.
The collection of log information is done by the Clogger (logger) and the distribution of the log information is processed under the Clogrouter dispatch (called the Log Routing manager). distributed to processing objects (such as Cfilelogroute and logging in the directory inherited from the Clogroute class, known as the log processor), after reading its source code repeatedly, I was more convinced of the design of yii, so layered processing, so that it easy to expand flexibility.
And the log information has the level of, such as general info, profile, trace, warning, error level, you can set up in the log route filter conditions, such as setting Cfileroute levels properties, you can only handle the specified level of log information.
As called in a program:

Yii::log ($message, Clogger::level_error, $category);

The corresponding process may be as follows:

    • Generate Clogger Instance
    • If Yii_debug, yii_trace_level are already defined as valid values, and the log level is not profile, the call backtracking information is generated and appended to the log information.
    • Call Clogger:: Log ($msg, $level, $category) to collect logs, in fact, the log is not written to the file, only temporarily in memory.

Question: When was the log written to the file?
after repeated tracking, I found that in the Init method of the Clogrouter class, the Application object's Onendrequest event is bound to the processor clogrouter::p rocesslogs (). The Onflush event-binding event handler Clogrouter::collectlogs method is also given to Yii::$_logger, which is used to write log flushes to files in a timely manner when there are too many logs in Yii::log (). The code is as follows:

/**
 * Initializes this application component.
 * This 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 '));

The Capplication::run () method defines:

 if ($this->haseventhandler (' onendrequest ')) {
 $this->onendrequest (New CEvent ($this));
 }

Here we can understand that Clogger (Yii::$_logger) simply collects the logs (logged into the content structure), and then, at the end of the program, the $app object calls Clogrouter's processlogs for log processing. Yii support log multiple paths by, for example: the same log can be written to the file, and can be displayed on the page, and even e-mail sent, and even recorded in the database, this is the configuration file in the Log:routes configuration, for the log:routes configuration of multiple elements, Implement multiple routing distributions. Log information is filtered and records are processed by the final log processor.
The tasks that the log processor will accomplish include the following: Get all the logs from the Clogger and filter (mainly levels, categories two definition Log:routes:levels/categories)

First, filter the logic in the Reference Cfilelogroute::collectlogs ():

 $logs = $logger->getlogs ($this->levels, $this->categories); Execution filtering, only the desired information

Log filtering is complete the next step is to finalize the log (such as writing to a file, logging to a database, etc.)

 Cfilelogroute::p rocesslogs ($logs);

But in this function, there is a small bug, only to determine whether the log directory is writable, not to determine whether the log file itself can be written. Cfilelogroute implemented a Linux-like log rotation function (logroate), and specified the size of the log file, considered very thoughtful, very perfect! I also want to learn from it and absorb its thoughts!
Configuration in protected/config/main.php:

' Preload ' =>array (' log '),
components => Array ('
       log ' =>array ('
         class ' => ' Clogrouter '),
         ' Routes ' =>array (
          Array (
            ' class ' => ' Cfilelogroute ',
            ' Levels ' => ' Error, Warning,trace '
          ),
         )
        )
       )

The definition log component needs to be preloaded (instantiated). The configuration uses Clogrouter as the log Routing manager and sets its log routing processor (routes property) and its configuration properties. Preload, the definition of the log attribute, is applied to the Cwebapplication object (see Configure invocation in Capplication::__construct, configure inherits from Cmodule). The log object (that is, the Clogrouter instance) is created by executing preloadcomponents () in the Cwebapplication constructor.
When a component is created and initialized, it is actually called cmodule::getcomponent, which uses yiibase::createcomponent to create the Component object and then invokes the INIT initialization of the component.
To read the Clogrouter::init () process, here are two key points, one is to create a log routing processor (that is, to determine the end of the log processing methods: Write files, mail delivery, etc.), the second is to the Application object binding onendrequest event handling Clogrouter ::p rocesslogs (). In Capplication::run () You do have code to run the Onendrequest event handling handle:

 if ($this->haseventhandler (' onendrequest ')) {
  $this->onendrequest (New CEvent ($this));
 }

That is, the final processing of the log (such as writing files, system logs, sending mail) occurs after the application is run. Yii uses event mechanisms to skillfully implement the association of events with handle handles.
That is, when the application runs, it executes the clogrouter::p rocesslogs, and the log is processed. Clogrouter is called the log Routing manager. Each log routing processor obtains the appropriate log from the Clooger object (using the filtering mechanism) for final processing.
Specifically, Yii's log system is divided into the following levels:

The log sender, which is called Yii::log ($msg, $level, $category) in the program, sends the log to the Clogger object
The Clogger object is responsible for staging log records in memory after the program runs, the log component (Clogroute) Processlogs method is activated to invoke the log router one by one to make the final processing of the log.

A more detailed overview of the process is as follows:

    • The preloadcomponents is invoked in Capplication::__construct (), which causes the log component (Clogroute) to be instantiated and initialized by invoking the Init method.
    • In the Init method of the Log component (Clogroute), which is the initialization log route and the CApplication object Onendrequest event binding process Processlogs. Onflush Event binding Process Collectlogs for Clooger components.
    • Other parts of the application send log information to the Clogger component by calling Yii::log (), and the Clogger component temporarily saves the log information in memory.
    • CApplication execution (in the Run method) activates the Onendrequest event, the bound event handler Processlogs is executed, and the log is written to the file. The log routing mechanism of Yii brings infinite flexibility to the expansion of the log system. and its multiple paths by the processing mechanism, the same log information can be handled in a variety of ways.

Here is a case where error level database errors are sent to the relevant maintenance personnel in a timely manner, and these logs are also recorded in the file. Planning ideas, sending emails and cell phone messages are two different features, Yii already has a log mail send component (logging/ cemaillogroute.php), but this component uses PHP's own mail function, the mail function needs to configure the SMTP host in php.ini, and use the unauthenticated way of sending, which is already completely unusable in the current situation. Instead, we need to use the SMTP delivery method with the authentication feature. Define the Log processor class Myemaillogroute in the protected/components/directory and let it inherit from Cemaillogroute, the main purpose of which is to override the Cemaillogroute::sendemail () method  , where the details of the handling of SMTP should be perfected (the focus of this article is on how to process the log, not on the mail).
Next, we can define log routing processing, edit protected/config/main.php, and add a new routing configuration to the routes component of the log component:

' Log ' =>array ('
class ' => ' Clogrouter ', '
routes ' =>array (
Array (
' class ' => ') Cfilelogroute ',
' Levels ' => ' Error, Warning,trace ',
),
Array (
' class ' => ' Myemaillogroute ', '
levels ' => ' error ', #所有异常的错误级别均为error, 
' categories ' => ' exception. CDBException ', #数据库产生错误时, all will produce CDBException exception.
' host ' => ' mail.163.com ', '
Port ' =>,
' user ' => ' jeff_yu ',
' password ' => ' Password ',
' timeout ' =>,
' emails ' => ' jeff_yu@gmail.com ', #日志接收人.
' sentfrom ' => ' jeff_yu@gmail.com ',
),

Through the above treatment, you can make it to achieve our goal, of course, you may be further expanded according to your needs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.