Log usage details of the YIIFramework framework tutorial

Source: Internet
Author: User
Tags what sql
This article mainly introduces the log usage of the YIIFramework framework tutorial, and analyzes the configuration, usage and related precautions of the Yii Framework log in detail based on the instance form, for more information about YII Framework log usage, see the following example. We will share this with you for your reference. The details are as follows:

Log function (1000 words omitted here)

Logs in YII are very powerful, allowing you to store the log information in the database, send it to the email, and store the log files. the opinion display page is, or even can be used for performance analysis.

Basic configuration of logs in YII:/yii_dev/testwebap/protected/config/main. php

'log'=>array(  'class'=>'CLogRouter',  'routes'=>array(    array(      'class'=>'CFileLogRoute',      'levels'=>'error, warning',    ),    // uncomment the following to show log messages on web pages    /*    array(      'class'=>'CWebLogRoute',    ),    */  ),),

Basic use of logs in YII:

You can use the YII: log and Yii: trace provided by Yii to output log information. you can see the difference between the two and see the definition.

Function definition

public static function trace($msg,$category='application'){  if(YII_DEBUG)    self::log($msg,CLogger::LEVEL_TRACE,$category);}public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application'){  if(self::$_logger===null)    self::$_logger=new CLogger;  if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)  {    $traces=debug_backtrace();    $count=0;    foreach($traces as $trace)    {      if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)      {        $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';        if(++$count>=YII_TRACE_LEVEL)          break;      }    }  }  self::$_logger->log($msg,$level,$category);}

$ Msg: The log information you want to output

$ Category: category of log information

$ Level: log information level:

Const LEVEL_TRACE = 'Trace '; used to debug the environment and track the program execution process
Const LEVEL_WARNING = 'warning'; warning information
Const LEVEL_ERROR = 'error'; fatal error message
Const LEVEL_INFO = 'info'; common prompt information
Const LEVEL_PROFILE = 'Profile '; performance debugging information

Basic usage example

<?phpclass DefaultController extends Controller{  public function actionCache ()  {    $category='system.testmod.defaultController';    $level=CLogger::LEVEL_INFO;    $msg='action begin ';    Yii::log($msg,$level,$category);  }}

Log output location in YII

The output location of logs in YII can be defined as many locations. You can modify the configuration file as follows:

'log'=>array(  'class'=>'CLogRouter',  'routes'=>array(    array(      'class'=>'CFileLogRoute',      'levels'=>'error, warning',    ),    // uncomment the following to show log messages on web pages    array(      'class'=>'CWebLogRoute',    ),  ),),

Not only log files, but also web pages.

In the configuration file:

Routes is used to configure the location of log output,
Class is the class name of log and log routing.
Levels is the top-level log and string sequence, which is well separated. Corresponds to constants in CLooger.

Note::

The log file is stored in/yii_dev/testwebap/protected/runtime/application. log.

The official log is very detailed, but the second half of the Chinese translation is missing. here we will complete the translation.

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 called Information Routing, for example, sending information to different destinations.

In Yii, Information Routing is managed by an application component called CLogRouter. It manages a series of things called log 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'=>'admin@example.com',        ),      ),    ),  ),)

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 comes with the convenient CLogFilter that may be used as the needed log filter in most cases. by default, CLogFilter will log a message with variables like $ _ GET, $ _ SERVER which often contains valuable system context information. CLogFilter can also be configured to prefix each logged message with session ID, username, etc ., which may greatly simplifying the global search when we are checking the numerous logged messages.

The framework may use the log filter CLogFilter to filter logs in many cases. By default, the CLogFilter log message contains many system context variables, such as $ _ GET and $ _ SERVER. CLogFilter can also be configured with prefix, session ID, and user name. when we check messages of countless records for each record, this may greatly simplify the search difficulty.

The following configuration shows how to enable logging context information. Note that each log route may have its own log filter. And by default, a log route does not have a log filter.

The following configuration shows how to enable the context information of logging. Note that each log route may have its own log filter. By default, no log filter is available for log routing.

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 logging call stack information in the messages that are logged by calling Yii: trace. this feature is disabled by default because it lowers performance. to use this feature, simply define a constant named YII_TRACE_LEVEL at the beginning of the entry script (before includingyii. php) to be an integer greater than 0. yii will then append to every trace message with the file name and line number of the call stacks belonging to application code. the number YII_TRACE_LEVEL determines how many layers of each call stack shocould be recorded. this information is special useful during development stage as it can help us identify the places that trigger the trace messages.

Starting from version 1.0.7, Yii logging can record messages in stack mode. This function is disabled by default because it reduces performance. To use this function, you only need to define a constant named YII_TRACE_LEVEL in the script (includingyii. php), that is, an integer greater than 0. Yii will append each file name and row number to be obtained by the application in the stack information. You can set the number of layers of the stack by setting YII_TRACE_LEVEL. This method is particularly useful in the development phase because it helps us determine where the tracing message is triggered.

5. Performance Profiling Performance analysis

Performance profiling is a special type of message logging. Performance profiling can be used to measure the time needed for the specified code blocks and find out what the performance bottleneck is.

Performance analysis is a special type of message records. Performance analysis can be used to measure the time required for a specified code block and identify the performance bottleneck.

To use performance profiling, we need to identify which code blocks need to be profiled. We mark the beginning and the end of each code block by inserting the following methods:

To use performance analysis logs, we need to determine which code blocks need to be analyzed. We need to add the following method at the beginning and end of the short code for analyzing performance:

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

Where blockID is an ID that uniquely identifies the code block.

BlockID is a unique ID that identifies a code block.

Note, code blocks need to be nested properly. That is, a code block cannot intersect with another. It must be either at a parallel level or be completely enclosed by the other code block.

Note that these methods cannot be cross-nested.

To show profiling result, we need to install a CLogRouter application component with a CProfileLogRoute log route. this is the same as we do with normal message routing. the CProfileLogRoute route will display the performance results at the end of the current page.

To display the analysis results, we need to add a CProfileLogRoute route for the CLogRouter. Then, you can use CProfileLogRoute to display the performance test results to the end of the current page.

6. Profiling SQL Executions analysis SQL execution

Profiling is especially useful when working with database since SQL executions are often the main performance bottleneck of an application. while we can manually insert beginProfile and endProfilestatements at appropriate places to measure the time spent in each SQL execution, starting from version 1.0.6, Yii provides a more systematic approach to solve this problem.

Analysis is particularly useful in database development, because SQL execution is often the main performance bottleneck of applications. Although we can manually insert beginProfile and endProfile where appropriate for each SQL execution to measure the time spent, Yii provides a more systematic solution to this problem starting from version 1.0.6.

By setting CDbConnection: enableProfiling to be true in the application configuration, every SQL statement being executed will be profiled. the results can be readily displayed using the aforementionedCProfileLogRoute, which can show us how much time is spent in executing what SQL statement. we can also call CDbConnection: getStats () to retrieve the total number SQL statements executed and their total execution time.

In the actual application, you can set CDbConnection: enableProfiling to analyze every SQL statement being executed. With CProfileLogRoute, the results can be easily displayed. It shows how long the SQL statement is being executed. We can also call CDbConnection: getStats () to analyze and retrieve the total number of SQL statements executed and their total execution time.

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.