_php examples of the log usage of the YII framework tutorial

Source: Internet
Author: User
Tags function definition session id unique id what sql smarty template yii

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

The function of the log (omit 1000 words here)

The logs in Yii are very good and powerful, allowing you to store log information in a database, send it to a set of emails, store the files in the document, and view the page as an indicator, even to perform performance analysis.

Basic configuration of the log 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 page s
    /* Array (
      ' class ' => ' Cweblogroute ',),
    *
/),

basic usage of the logs in Yii :

You can use the Yii::log and Yii::trace provided by Yii to do the output of the log information, the difference between the two to see the definition is known.

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: Level of log information:

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

Examples of basic use methods

<?php
class 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 log in Yii can be defined as many locations. Primarily through configuration file modifications such as:

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


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

In the configuration file:

Routes is used to configure the location of the log output.
Class is the log, the name of the log route
Levels is the top of the log, the string sequence, with good segmentation. Specific corresponding constants in the Clooger

Note :

The location of the log files is:/yii_dev/testwebap/protected/runtime/application.log

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

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

1. Information recording

Information can be recorded by 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 logging information, we need to specify that its classification and level classification is a string that is similar in format to a path alias. For example, if a piece of information is recorded in Ccontroller, we can use System.web.CController as a taxonomy. 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 ordinary information.
Profile: This is a performance overview (profile). A more detailed description will be available immediately below.
warning: This is used for warning (warning) information.
Error: This is for fatal error (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, 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 is responsible for managing a series 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 preload a Clogrouter application component. We also need to configure its routes properties for those log routes we want. The following code shows an example of the desired application configuration:

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 example above, we have defined two log routes. The first is Cfilelogroute, which saves the information in a file located in the runtime directory of the application. And only levels are trace or info, sorted with system. The initial information is saved. The second route is Cemaillogroute, which sends the information to the specified email address and is sent only if the level is error or warning.

In Yii, the following several 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 information to a file in the Application Runtime directory.
Cweblogroute: Displays the information at the bottom of the current page.
cprofilelogroute: Displays overview (profiling) information at the bottom of the page.

Information: Information routing occurs when the Onendrequest event that is the last 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 so that the information is logged smoothly.

3. Information filtering

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

Because the classification of information is similar to the xxx.yyy.zzz format, we can see it as a classification hierarchy. 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 context information

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

The framework comes with the convenient clogfilter is used as the needed log filter in most. By default, Clogfilter'll log a message with variables like $_get, $_server which often contains the system context Information. Clogfilter can also be 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, Clogfilter log messages contain a number of variables for system context information, such as $ _get,$_server. Clogfilter can also be configured with prefix session ID, username, etc., which we check for countless records of messages per recorded message, which may greatly simplify the search difficulty

The following configuration shows to enable logging context information. Note this 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 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 (Array (' class ' => ') cfilelogr
      Oute ', ' Levels ' => ' error ', ' Filter ' => ' Clogfilter ',), ... other log routes ... ),
    ),
  ),
)

Starting from version 1.0.7, YII supports logging call stack information at the messages that are 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 to every trace, 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 should is recorded. This information is 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, the logging of Yii can be used to log messages in 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 entry script (includingyii.php) that is an integer greater than 0. Yii appends the stack information to each file name and line number to which the application will be added. You can set the stack number of layers by setting yii_trace_level. This is especially 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 kind of special type of message logging. Profiling can be used to measure the time required for a specified code block and to identify what the performance bottleneck is.

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

To use the profiling log, we need to determine which blocks of code need to be parsed. We want to add the following methods to the short start and end of the analysis performance code:

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 the code block.

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

Note that these methods cannot cross nesting

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

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

6. Profiling SQL executions Analysis SQL execution

Profiling is especially useful then working with database since SQL executions are 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.

Analysis is particularly useful in database development, because SQL execution is often a major performance bottleneck for applications. Although we can manually insert Beginprofile and endprofile at the appropriate place for each SQL execution to measure the time spent, Yii offers a more systematic approach to this problem, starting with version 1.0.6.

By setting Cdbconnection::enableprofiling to is true in the application configuration, every SQL statement being would be profiled. The results can be readily displayed using the Aforementionedcprofilelogroute, which can show us how much more time are 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, set the cdbconnection::enableprofiling love to parse each executing SQL statement. With Cprofilelogroute, the results can be easily displayed. It can show how long it takes us to execute what SQL statement. We can also call Cdbconnection:getstats () to parse the total number of executions and the total execution time of the SQL statement.

More about Yii related content readers can view the site topics: "Yii framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming Program", " Summary of PHP string usage, Introduction to PHP+MYSQL database operations, and a summary of PHP common database operations Tips

I hope this article will help you with the PHP program design based on the YII framework.

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.