YII Framework Framework Tutorial Log usage detailed, yiiframework_php tutorial

Source: Internet
Author: User
Tags configuration php getting started with php session id what sql yii

A detailed log usage of the YII Framework Framework tutorial, Yiiframework


The example in this article describes the YII framework log usage. Share to everyone for your reference, as follows:

function of the log (1000 words omitted here)

Yii log is very good and powerful, allows you to put log information into the database, sent to the development of email, stored in the file, the opinion display page is, even can be used to do performance analysis.

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

' Log ' =>array (  ' class ' = ' Clogrouter ',  ' routes ' =>array ('      class ' = ') ' Cfilelogroute ',      ' levels ' = ' Error, warning ', '    ),    //Uncomment the following to show log messages on Web page s    /* Array (      ' class ' = ' Cweblogroute ',    ),    *  /),

basic usage of logs in Yii :

You can use the Yii::log and Yii::trace provided by Yii to make the output of the log information, the difference between the two look at the definition to know.

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: Log information belongs to Category

$level: Level of log information:

Const level_trace= ' trace '; For debugging environments, tracking program execution processes
Const level_warning= ' WARNING '; warning message
Const level_error= ' error '; Fatal error message
Const level_info= ' info '; general tip information
Const level_profile= ' profile '; Performance debugging information

Examples of basic use methods

<?phpclass Defaultcontroller extends controller{public  function Actioncache ()  {    $category = ' System.testmod.defaultController ';    $level =clogger::level_info;    $msg = ' action begin ';    Yii::log ($msg, $level, $category);  }}

Output location of logs in Yii

The output location of the logs in Yii mentioned above can be defined as many locations. Primarily through configuration file modifications such as:

' Log ' =>array (  ' class ' = ' Clogrouter ',  ' routes ' =>array ('      class ' = ') ' Cfilelogroute ',      ' levels ' = ' Error, warning ', '    ),    //Uncomment the following to show log messages on Web p Ages    Array (      ' class ' = ' Cweblogroute ',    ),),  

Not only the output to the log file, but also the output to the Web page.

In the configuration file:

Routes is used to configure the location of the log output,
Class is the log, and the name of the log route
Levels is the top of the log, the string sequence, and is good to split. correspond to constants in Clooger

Note :

The log file is stored in the following location:/yii_dev/testwebap/protected/runtime/application.log

The official log introduction is very detailed, but the latter part of the Chinese translation is missing, here to complete the translation.

YII provides a flexible and extensible logging capability. Logged logs can be categorized by log level and information classification. By using the level and classification filters, the selected information can be further routed to different destinations, such as a file, Email, browser window, etc.

1. Information recording

Information can be recorded by Yii::log or Yii::trace. The difference is that the latter only logs information when the application is running in debug mode (debug modes).

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

When logging information, we need to specify its classification and level classification as a string formatted like a 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 in development.
Info: This is used to record common information.
Profile: This is a performance overview (profile). A more detailed description is now available.
warning: This is used for warning (warning) information.
Error: This is used for fatal errors (fatal error) information.

2. Information routing

The information recorded through Yii::log or yii::trace is stored in memory. We usually need to display them in the browser window, or save them to some persistent storage such as files and emails. This is called information routing, for example, sending messages to different destinations.

In Yii, information routing is managed by an application component called Clogrouter. It is responsible for managing a range of things called log routing. Each log route represents a separate log destination. The information sent through a log route is filtered by their level and classification.

To use information routing, we need to install and pre-load a Clogrouter application component. We also need to configure its Routes property for those log routes that we want. The following code shows an example of a desired application configuration:

Array (...  ') Preload ' =>array (' log '),  ' components ' =>array (...    ') Log ' =>array ' (      ' class ' = ' Clogrouter ',      ' routes ' =>array ('          class ' = ') ' Cfilelogroute ',          ' levels ' = ' Trace, info ',          ' categories ' = ' system.* ', ', ', '        array (          ' Class ' = ' Cemaillogroute ',          ' levels ' = ' Error, warning ',          ' emails ' = ' admin@example.com ',      ),    ),  ),)

In the example above, we have defined two log routes. The first is Cfilelogroute, which stores the information in a file located in the Application Runtime directory. And only the level is trace or info, categorized with system. The initial information will be saved. The second route is Cemaillogroute, which sends the information to the specified email address and is only sent if the level is error or warning.

In Yii, the following log routes are available:

Cdblogroute: Saves the information to a table in the database.
cemaillogroute: Send the message to the specified email address.
Cfilelogroute: Saves the information to a file in the Application Runtime directory.
Cweblogroute: Displays information at the bottom of the current page.
cprofilelogroute: Displays overview (profiling) information at the bottom of the page.

Information: Information routing occurs at the end of the current request period when the Onendrequest event is triggered. To explicitly terminate the current request process, call Capplication::end () instead of die () or exit (), because Capplication::end () will trigger the Onendrequest event so that the information is successfully logged.

3. Information filtering

As we mentioned, information can be filtered by their levels and classifications before they are sent to a log route. This is done by setting the levels and Categories properties for the corresponding log route. Multiple levels or classifications should be concatenated with commas.

Since information classification is similar to XXX.YYY.ZZZ format, we can consider it as a classification level. Specifically, we say that XXX is the parent of xxx.yyy, and Xxx.yyy is the parent of xxx.yyy.zzz. So we can use xxx.* to represent the classification of XXX and all of its children and grandchildren.

4. Record contextual information

From version 1.0.6, we can set up additional contextual information such as PHP's predefined variables (such as $_get, $_server), session ID, user name, etc. This is achieved by specifying the Clogroute::filter property of a log route for an appropriate log filtering rule.

The framework comes with the convenient clogfilter, the May is used as the needed log filter in most cases. By default, Clogfilter would log a message with variables like $_get, $_server which often contains valuable system context Information. Clogfilter can also is configured to prefix each logged message with session ID, username, etc., which may greatly simplif Ying The global search when we are checking the numerous logged messages.

The framework may use log filter Clogfilter to filter logs in many cases. By default, the Clogfilter log message contains many variables for system context information, such as $ _get,$_server. Clogfilter can also be configured to prefix sessions with session IDs, user names, etc., which can greatly simplify the search difficulty when we examine the messages for each record in countless recorded messages.

The following configuration shows how to enable logging context information. Note: Each log route may has its own log filter. And by default, the A log route does not has a log filter.

The following configuration shows how to enable contextual information for logging. Note that each log route may have its own log filter. By default, log routing does not have a log filter.

Array (...  ') Preload ' =>array (' log '),  ' components ' =>array (...    ') Log ' =>array ' (      ' class ' = ' Clogrouter ',      ' routes ' =>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 is logged by calling Yii::t Race. This feature was 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 including yii.php) to is an integer greater than 0. Yii would then append-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 all call stacks should be recorded. This information was particularly useful during development stage as it can help us identify the places that trigger the TR Ace messages.

Starting with version 1.0.7, Yii logging can log messages on a stack, which is turned off by default because it degrades performance. To use this feature, simply define a constant named Yii_trace_level in the Portal script (formerly Includingyii.php), which is an integer greater than 0. Yii appends the stack information to each file name and line number the application is going to. You can set the number of layers for the stack by setting Yii_trace_level. This approach is particularly useful in the development phase because it helps us determine where to trigger the trace message.

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 Performan Ce bottleneck is.

Performance analysis is a special type of message logging. Profiling can be used to measure the time required for a specified block of code and to find out what the performance bottleneck is.

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 the profiling logs, we need to determine which blocks of code need to be parsed. We want to add the following method to the beginning and end of the code for analyzing performance:

Yii::beginprofile (' Blockid '), .... code block being profiled ... Yii::endprofile (' Blockid ');

Where Blockid is a ID that uniquely identifies the code block.

Where Blockid is a unique ID that identifies a code block.

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

Note that these methods cannot cross-nest

To show profiling result, we need to install a Clogrouter application component with a Cprofilelogroute log route. The same as we do with normal message routing. The Cprofilelogroute route would display the performance results at the end of the current page.

To show the results of the analysis, we need to increase the Cprofilelogroute route for Clogrouter. The performance test results can then be displayed at the end of the current page through Cprofilelogroute.

6. Profiling SQL executions Parsing SQL execution

Profiling is especially useful if working with database since SQL executions be often the main performance bottleneck O F an application. While we can manually inserts 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.

Parsing in database development is particularly useful because SQL execution is often the main performance bottleneck for your application. Although we can manually insert Beginprofile and endprofile to measure the time spent in each of the appropriate places for SQL execution, YII provides a more systematic approach to solving this problem starting with version 1.0.6.

By setting Cdbconnection::enableprofiling to being true in the application configuration, every SQL statement being executed would be profiled. The results can readily displayed using the Aforementionedcprofilelogroute, which can show us how much time was spent in Executing what SQL statement. We can also call Cdbconnection::getstats () to retrieve the total number of SQL statements executed and their total execution Time.

In the actual application, you can parse each SQL statement that is executing by setting cdbconnection::enableprofiling love. With Cprofilelogroute, the results can be easily displayed. It can show how much time we spend on what SQL statements we are executing. We can also call Cdbconnection:getstats () to parse the total number of executions and the total execution time of the retrieved SQL statement.

For more information on YII related content readers can view this site topic: "YII framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Basic Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming introduction Tutorial", " PHP String Usage Summary, "Getting Started with Php+mysql database operations" and "PHP Common Database Operations Skills Summary"

It is hoped that this article is helpful to the PHP program design based on YII framework.

Articles you may be interested in:

    • PHP YII Framework Development Little tricks Model (models) Rules custom validation rule
    • Nginx configuration PHP Rewrite rules example of Yii and cakephp framework
    • How to install the Yii framework using composer
    • Yii method for executing SQL statements using the Migrate command
    • Yii Framework framework uses YIIC to quickly create migrate usage examples of YII applications
    • Yii Framework Framework tutorial using YIIC quickly create a detailed application of Yii
    • The internationalization realization method of YII Framework frame Tutorial
    • A detailed description of the caching usage of YII Framework Framework Tutorial
    • A detailed description of the security scheme for YII Framework Framework Tutorial
    • An explanation of the exception handling of YII Framework Tutorial
    • Example of common rules for YII rules

http://www.bkjia.com/PHPjc/1110087.html www.bkjia.com true http://www.bkjia.com/PHPjc/1110087.html techarticle for a detailed description of the logging usage of the YII Framework Framework tutorial, Yiiframework This example describes the YII framework log usage. Share to everyone for your reference, as follows: The role of the log (... )

  • Related Article

    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.