Yii Framework official tutorial supplemental version 45-topic: Logging

Source: Internet
Author: User
Yii provides a flexible and scalable log function. Logs can be classified by log level and information classification. By using the level and category filters, the selected information can be further routed to different destinations, such as...



Yii provides a flexible and scalable log function. Logs can be classified by log level and information classification. By using level and category filters, the selected information can be further routed to different destinations, such as a file, Email, and browser window.

1. Information record

Information can be recorded through Yii: log or Yii: trace. The difference is that the latter only records information when the application is running in debug mode.


Yii::log($message, $level, $category);Yii::trace($message, $category);

When recording information, we need to specify its classification and level classification as a string in a format similar to the path alias. For example, if a piece of information is recorded in CController, we can use system. web. CController as the classification. The information level should be one of the following values:

  • Trace: this is the level used in Yii: trace. It is used to track the execution process of a program during development.

  • Info: this is used to record common information.

  • Profile: This is the Performance Overview (profile ). More details will be provided below.

  • Warning: this is used for warning information.

  • Error: this is used for fatal error information.

2. Information Routing

Information recorded through Yii: log or Yii: trace is stored in memory. We usually need to display them in a browser window, or save them to some persistent storage such as files and emails. This is calledInformation RoutingFor example, send messages to different destinations.

In Yii, Information Routing is managed by an application component called CLogRouter. It manages a seriesLog routing. Each log route represents a separate log destination. Information sent through a log route is filtered by their level and category.

To use information routing, we need to install and pre-load a CLogRouter application component. We also need to configure its routes attribute as the log route we want. The following code demonstrates a required application configuration example:


array(    ......    'preload'=>array('log'),    'components'=>array(        ......        'log'=>array(            'class'=>'CLogRouter',            'routes'=>array(                array(                    'class'=>'CFileLogRoute',                    'levels'=>'trace, info',                    'categories'=>'system.*',                ),                array(                    'class'=>'CEmailLogRoute',                    'levels'=>'error, warning',                    'emails'=>[email protected]',                ),            ),        ),    ),)

In the preceding example, two log routes are defined. The first is CFileLogRoute, which stores the information in a file in the application runtime directory. In addition, only information whose level is trace or info and whose category starts with system. will be saved. The second route is CEmailLogRoute, which sends the information to the specified email address and sends the message only when the level is error or warning.

In Yii, the following log routes are available:

  • CDbLogRoute: save the information to the database table.

  • CEmailLogRoute: sends information to the specified Email address.

  • CFileLogRoute: save the information to a file in the application runtime directory.

  • CWebLogRoute: displays information at the bottom of the current page.

  • CProfileLogRoute: displays the overview information at the bottom of the page.

Information:Information Routing occurs when the last onEndRequest event of the current request cycle is triggered. To explicitly terminate the current request process, call CApplication: end () instead of using die () or exit () because CApplication: end () will trigger the onEndRequest event, in this way, the information will be recorded smoothly.

3. information filtering

As we mentioned, information can be filtered by their level and category before they are sent to a log route. This is done by setting the levels and categories attributes of the corresponding log route. Use commas to connect multiple levels or categories.

Because information classification is similar to xxx. yyy. zzz, we can regard it as a classification level. Specifically, xxx is the parent level of xxx. yyy, and xxx. yyy is the parent level of xxx. yyy. zzz. In this way, we can use xxx. * to indicate the classification of xxx and all its sublevels and grandchildren.

4. record context information

Starting from version 1.0.6, we can set the additional context information to record, such as PHP pre-defined variables (such as $ _ GET, $ _ SERVER), session ID, and user name. This is achieved by specifying the CLogRoute: filter attribute of a log route as a suitable log filter rule.

The framework uses a CLogFilter that can be used for most log filtering. by default, CLogFilter records a variable that contains (such as $ _ GET, which usually contains the system context variable value, $ _ SERVER, etc. CLogFilter can also be used to configure the session ID and user name before each log information. This will bring great convenience when we want to find the location of log information.

The following configuration shows how to enable the record context information. Each log route has its own log filter, but by default, the log route does not contain the log filter.


array(    ......    'preload'=>array('log'),    'components'=>array(        ......        'log'=>array(            'class'=>'CLogRouter',            'routes'=>array(                array(                    'class'=>'CFileLogRoute',                    'levels'=>'error',                    'filter'=>'CLogFilter',                ),                ...other log routes...            ),        ),    ),)

Starting from version 1.0.7, Yii supports recording the callback stack information in the log records returned by calling Yii: trace. This feature is canceled by default because this reduces performance. To use this feature, you only need to define a constant named YII_TRACE_LEVEL greater than 0 in the portal script (including yii. before php), then Yii will add the file name and row number of the application code callback stack after each trace information. YII_TRACE_LEVEL determines that the hierarchy of each callback stack will be recorded. This information is useful during development because it helps us determine the location where trace information is triggered.

5. Performance analysis

Performance analysis is a special logging type. Performance analysis can be used to measure the running time of a specified code block and identify performance bottlenecks.

When using performance analysis, we need to specify the code block to be analyzed. We can insert the following code to mark the beginning and end of each code block:


Yii::beginProfile('blockID');...code block being profiled...Yii::endProfile('blockID');

BlockID indicates the unique identifier of a code block.

Note that the code block must be reasonably nested. That is to say, a code block cannot be cross-nested with another code block: it is either parallel or completely closed and contained in another code block.

To display the analysis results, you must install a CLogRouter application component that contains the CProfileLogRoute log route. Like other information routing, CProfileLogRoute routing displays performance analysis results at the bottom of the current page.

6. SQL execution analysis

Performance analysis is particularly useful when processing database operations, because SQL execution is often a major performance bottleneck for applications. Of course, we can insert the beginProfile and endProfile statements in each SQL execution, starting from version 1.0.6, but Yii provides a more systematic way to solve this problem.

By setting CDbConnection: enableProfiling to true in application configuration, every executed SQL statement will be analyzed. the result can be displayed by setting the CProfileLogRoute mentioned above, so that we can know the execution time of each SQL statement. In addition, we can also call CDbConnection: getStats () to retrieve the number of SQL statement executions and total execution time.

The above is an additional version of the Yii Framework official tutorial 45-topic: log record content. For more information, see The PHP Chinese website (www.php1.cn )!

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.