Common log operations for the YII framework in PHP

Source: Internet
Author: User
Tags yii
This article mainly introduces the PHP yii framework of the common log operation summary, including the message is too small and formatting and other basic content, the need for friends can refer to the following





Log
Yii provides a highly customizable and highly scalable log framework. Depending on the usage scenario, you can easily record, filter, and merge messages, such as text files, database files, and messages.



The logging framework using YII contains the following steps:



Methods for invoking logging


    • Configure the filter and export settings for the log in the main app's configuration file (for example, web.php below Basic)

    • Check log information after filtering in different scenarios

    • Record log


Logging is simply a simple way to invoke the following:


    • [[Yii::trace ()]]: Records related messages about the run of a piece of code. Primarily for the development environment.

    • [[Yii::info ()]]: used when some useful information is recorded in some locations.

    • [[Yii::warning ()]]: Use this method when something outside of the expectation occurs.

    • [[Yii::error ()]]: Call this method to log relevant information when a fatal problem that needs to be resolved immediately occurs.


Although these methods record information based on different level and type, they actually call the same method function ($message, $category = ' application '). Where $message is the information to be recorded, $category represents the attribution class for this log. The following code indicates that a trace type of information is logged under the default ' Application ' category.


Yii::trace (' Start calculating average revenue ');


Tip: The $message of a record can be a simple string or a complex array or object. You should choose the right type of $message according to the responsibilities of logging in different scenarios. By default, if you record a $message that is not a string, the log will call the [[Yii\helpers\vardumper::export ()]] method to output a string type of message when it is exported.



For better organization management and filtering of log messages, it is usually appropriate to assign each log a suitable category. You can choose a classification that has a distinct level of distinction, which makes it easier to sift through different categories of logs for different purposes. A simple and effective naming method is to use the magic constant method of PHP as the name of the classification. The core code inside the YII framework is doing this when logging. For example:


Yii::trace (' Start calculating average revenue ', __method__);


Where a constant method appears, it represents the name of the current method (plus the full prefix of the class to which the current method belongs). For example, if the Calculate method inside the App\controllers\revenuecontroller class has the above line of code, then this method means ' app\controllers\ Revenuecontroller::calculate '.



Tip: The method described above is in fact just a simple use of the [[Yii\log\logger::log () |log ()]] method of the Singleton object [[Yii\log\logger|logger Object]], which we can do by Yii::getlogger () method to obtain the singleton object. When we have logged enough log information or the current application is finished running, the log object will call the [Yii\log\dispatcher|message Dispatcher]] method to write the logged log information to the configured destination.



Log targets
A log Target is an instance of [[Yii\log\target]] or its subclasses. It filters logs based on severity ratings and classification classes, and then exports the logs to the appropriate media. For example, a [[Yii\log\dbtarget|database target]] object will export the filtered log information to the corresponding database.
You can register multiple log targets at the log component in your app's configuration file, as follows:


return [//the "log" component must be loaded during bootstrapping time ' bootstrap ' = [' log '], ' components ' = [  ' Log ' = = ['    targets ' = ['      class ' = '        yii\log\dbtarget ',        ' levels ' and ' = ' error ', ' warning '] ,      ],      [        ' class ' = ' Yii\log\emailtarget ',        ' levels ' = [' Error '],        ' categories ' and ' = ' yii\ Db\* '],        ' message ' = = [' from          ' = = ' log@example.com '], ' to ' and '          = ' admin@example.com ', ' Developer@example.com '],          ' subject ' = ' Database errors at example.com ',        ],      [],    ],  ],],;


Note: The log component must be configured in bootstrap in order to distribute the log information to the corresponding log target.
In the above code, two log target is registered in [[Yii\log\dispatcher::targets]].



The first filters out the error and warning messages and saves the information to the database.
The second filters out the error messages that begin with yii\db* and sends the messages to admin@example.com and developer@example.com.
Yii has the following built-in log targets, you can refer to the API documentation to learn exactly how to configure and use them.


    • [[Yii\log\dbtarget]]: Save the log information to the database.

    • [[Yii\log\emailtarget]]: Send the log information to the designated mailbox, the above example is.

    • [[Yii\log\filetarget]]: Writes the log to the file.

    • [[[Yii\log\syslogtarget]]: Call the PHP syslog () method to write the log to the system log.


Next, let's take a look at the features of the common log target.



Message filtering
For each log Target, you can configure its [[Yii\log\target::levels|levels]] and [[Yii\log\target::categories|categories]] The attribute class sets the severity of it and the classification of the attribution.
The [[Yii\log\target::levels|levels]] property takes one or more values from an array that contains the following values:


    • Error: Message recorded for [[Yii::error ()]]

    • Warning: corresponding to [[Yii::warning ()]] recorded messages

    • Info: corresponding to [[Yii::info ()]] recorded information

    • Trace: Corresponds to the information recorded by [[Yii::trace ()]].

    • Profile: The information that corresponds to [[Yii::beginprofile ()]] and [[Yii::endprofile ()]] is recorded, in this way more details are recorded below.


If you do not specify a value for [[Yii\log\target::levels|levels]], then any level information will be recorded.



The value of [[Yii\log\target::categories|categories]] property is an array, and the value inside the array can be a specific category name or a matching pattern similar to regular. Only if Target can find the corresponding class name in this array or match a matching pattern, will he process the message. The matching pattern here is composed of a number appended to the name of the category. If the classification matches exactly the character of the matching pattern, then the corresponding match is found in this category. For example, in the class [[Yii\db\command]] Yii\db\command::execute and Yii \db\command:: The Query method uses the class name class to record related log information, then they all match the pattern yii\db*



Similarly, if we do not specify [[Yii\log\target::categories|categories]], then the log information for each category will be processed.
In addition to setting a whitelist of classifications by using [[Yii\log\target::categories|categories]] properties, you can also set a blacklist of categories by using the [[Yii\log\target::except|except]] property. The classified log information belonging to the blacklist is not processed by target.



The following configuration specifies a classification that matches yii\db* or yii\web\httpexception:*, but does not include the classification of yii\web\httpexception:404, and it only handles log information for errors and warnings.


[' class ' = ' yii\log\filetarget ', ' levels ' = [' Error ', ' warning '], ' categories ' = [  ' yii\db\* ',  ' Yii \web\httpexception:* ',], ' except ' = [  ' yii\web\httpexception:404 ',],


Note: When the wrong handle catches an exception to HTTP, the logged log information is in this format of Yii\web\httpexception:errorcode
Records such as [[Yii\web\notfoundhttpexception]] will be recorded as yii\web\httpexception:404
Message formatting
Log targets uses multiple formats to export logs. For example, if your log target is [[Yii\log\filetarget]], then when you log in your program, you should find the following information similar to the file Runtime/log/app.log record:


2014-10-04 18:10:15 [:: 1][][-][trace][yii\base\module::getmodule] Loading Module:debug


By default, [[[Yii\log\target::formatmessage ()]]: will help us format the log information in the following format:


Timestamp [IP address][user id][session id][severity level][category] Message Text


You can customize the prefix of the log by configuring a custom callback function for the [[Yii\log\target::p Refix]] property. The following code implements the user ID (IP address, SessionID, and other sensitive information) preceded by each log message as a result of personal privacy being removed.


[' class ' = ' yii\log\filetarget ', ' prefix ' = function ($message) {  $user = Yii:: $app->has (' user ', true)? Yii:: $app->get (' user '): null;  $userID = $user? $user->getid (false): '-';  Return "[$userID]";}]


In addition to the log message prefix, the target of the log also attaches some contextual information to each batch of log records. By default, the global PHP variable contains $_get, $_post, $_files, $_cookie, $_session, and $_server. You can adjust the global variables for logging by configuring [[Yii\log\target::logvars]]. The following code indicates that only $_server related variables are logged.


[' class ' = ' Yii\log\filetarget ', ' logvars ' = ' [' _server '],]


When ' Logvars ' is empty, the associated contextual information is not logged. If you want to customize the way context information is provided, you can override the [[Yii\log\target::getcontextmessage ()]] method.



Trace level of the message
In the process of development, we always expect to know where each log message is coming from. In Yii you can do this by configuring the [[Yii\log\dispatcher::tracelevel|tracelevel]] property. Examples of configuration are as follows:


return [' Bootstrap ' = [' log '], ' components ' and ' ['  log ' = ' = '    traceLevel ' + yii_debug? 3:0,    ' Ta Rgets ' = [...],],]  ,;


The above example sets [[Yii\log\dispatcher::tracelevel|tracelevel]] to 3 when Yii_debug is true, whereas the inverse is set to 0. What does that mean? 3 means that each log record records the three-tier stack call information associated with it, and 0 indicates that no related stack call information is logged



Tip: It is not necessary to always record the stack information of the call and compare the consumption performance. Therefore, you should only use this feature when you are developing or debugging.
Emptying and exporting of messages
As stated above, the recorded message is stored in the form of an array in [[Yii\log\logger|logger Object]]. In order to limit the amount of memory that this array consumes, when the array contains content that reaches a certain volume, it is transferred from memory to the corresponding target (file, database ...). In You can determine the size of a quantity by setting the value of [[Yii\log\dispatcher::flushinterval|flushinterval]]. Like this:


return [' bootstrap ' + = [' log '], ' components ' and ' = '  log ' = ' = '    flushinterval ' + +,  //default is +    ' targets ' = [...],], [],]  ;


Note: The memory will also be refreshed at the end of the app's run, so that the target of the log can record the complete information.
This action does not occur immediately when the log information is brushed from the memory to the corresponding place of storage. In fact, as in the above, it happens when the log size in memory reaches a certain level. You can achieve the purpose of the modification by configuring the [[Yii\log\target::exportinterval|exportinterval]] value of the different Target as in the following example:


[' class ' = ' Yii\log\filetarget ', ' exportinterval ' = +,//default is 1000]


Because of the empty and exported settings, by default you will not see the log message immediately under the log target when you call Yii::trace () or other logging methods. This is a problem for some long-running console programs. However, this problem can be solved by means of the following code, which you need to put [[[Yii\log\dispatcher::flushinterval|flushinterval]] and [[Yii\log\target::exportinterval The value of |exportinterval]] is set to 1:


return [' bootstrap ' + = [' log '], ' components ' = = [' log ' = ' = '    flushinterval ' + 1,    ' targets ' = > [      [        ' class ' = ' Yii\log\filetarget ',        ' exportinterval ' = 1,      ],    ],  ],],;


Note: Emptying and exporting log messages so frequently can degrade the performance of the system.



Targets of switching logs
You can suppress the Target of the log by setting the [[Yii\log\target::enabled|enabled]] property. As described in the following code:


Yii:: $app->log->targets[' file ']->enabled = false;


The code above requires you to have a configuration in the configuration file:


return [' bootstrap ' + = [' log '], ' components ' and ' [' log ' = ' = ' targets ' + ['      file ' = ' + '        cl The ' yii\log\filetarget ', ' the '      db ' = [        ' class ' = ' Yii\log\dbtarget ',      ]  ,], ],];


Create a new target
First, it is very simple to create a new log target. The main thing you do is to implement the [[Yii\log\target::export ()]] method and send the message [[Yii\log\target::messages]] of the array type to the specified storage medium. In this procedure you can call the [[Yii\log\target::formatmessage ()]] method to format each log message. For more details, you can find detailed information in the YIID release.



Performance evaluation
Performance evaluation is a very special kind of log record. It is commonly used to  on the execution time of certain modules, which is where the problem of performance is found. For example, [[Yii\db\command]] This class uses the performance evaluation log to get the time spent on each SQL query.



To use this class of logs, you first have to make sure that you are testing the range of code. Then between each piece of code you should keep them closed, just like this:


\yii::beginprofile (' Mybenchmark ');.. code block being Profiled...\yii::endprofile (' Mybenchmark ');


Mybenchmark is just an identity for you to quickly locate when you view the corresponding log records.
The Beginprofile and endprofile can be nested again, but the correct closing relationship must be guaranteed, as shown below:


\yii::beginprofile (' Block1 ');//Some code to be profiled\yii::beginprofile (' Block2 ');  Some other code to be Profiled\yii::endprofile (' Block2 '); \yii::endprofile (' Block1 ');


If there is an error in the closing relationship above, the corresponding record will not work correctly.



For each piece of code being evaluated, the level of the log is profile. You can configure the information in the target of the log and export them. Yii built Yii debugger to show the results of the evaluation.



The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!


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.