Summary of common log operations of PHP Yii Framework

Source: Internet
Author: User
This article mainly introduces the summary of common log operations in the PHP Yii Framework, including basic content such as message skipping and formatting. For more information, see Logs
Yii provides a highly customized and scalable log framework. Depending on the scenario, you can easily record, filter, and merge various messages, such as text files, database files, and emails.

The log framework using Yii includes the following steps:

Call the log record method

  • Configure log filtering and export settings in the configuration file of the main application (for example, web. php under basic ).
  • Check the filtered log information in different scenarios
  • Record logs

Logging is actually a simple way to call the following method:

  • [[Yii: trace ()]: records messages about code running. It is mainly used in the development environment.
  • [[Yii: info ()]: used to record useful information in some locations.
  • [[Yii: warning ()]: This method is used when something out of expectation occurs.
  • [[Yii: error ()]: This method is called to record relevant information when a critical problem needs to be resolved immediately occurs.

Although these methods record information based on different levels and types, they actually call the same method function ($ message, $ category = 'application '). $ Message indicates the information to be recorded, and $ category indicates the log owner class. The following code records a trace type under the default 'application' category.

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

Tip: the recorded $ message can be a simple string or a complex array or object. You should select the appropriate $ message type based on the logging responsibilities in different scenarios. By default, if the $ message you recorded is not a String, logs will call [[yii \ helpers \ VarDumper: export ()] During export. method to output a message of the string type.

In order to better organize and manage and filter log messages, a proper category should be allocated for each log. You can select a type with a clearly classified meaning to filter logs of different categories for different purposes. A simple and effective naming METHOD is to use the magic constant METHOD of PHP as the classification name. The core code in the Yii Framework does this when logging. For example:

Yii::trace('start calculating average revenue', __METHOD__);

Where a constant METHOD appears, it indicates the name of the current METHOD (and adds the complete prefix of the class to which the current METHOD belongs ). For example, if the calculate METHOD in the app \ controllers \ RevenueController class has the above line of code, the METHOD indicates 'app \ controllers \ RevenueController :: calculate '.

Tip: The method mentioned above is actually only [yii \ log \ Logger: log () of [[yii \ log \ logger | Logger object] of the singleton object () | log ()]: The Singleton object can be obtained through the Yii: getLogger () method. When we record enough log information or the current application is running, the log object will call [yii \ log \ Dispatcher | message dispatcher] to write the recorded log information to the configured destination location.

Log targets
A log target is an instance of [[yii \ log \ Target] or its subclass. It filters logs based on severe levels and categories, and then exports the logs to appropriate media. For example, a [[yii \ log \ DbTarget | database target] object exports the filtered log information to the corresponding database.
You can register multiple log targets in the log component of the application configuration file, as shown below:

return [// the "log" component must be loaded during bootstrapping time'bootstrap' => ['log'],'components' => [  'log' => [    'targets' => [      [        'class' => 'yii\log\DbTarget',        'levels' => ['error', 'warning'],      ],      [        'class' => 'yii\log\EmailTarget',        'levels' => ['error'],        'categories' => ['yii\db\*'],        'message' => [          'from' => ['log@example.com'],          'to' => ['admin@example.com', 'developer@example.com'],          'subject' => 'Database errors at example.com',        ],      ],    ],  ],],];

Note: The log component must be configured in bootstrap to distribute the log information to the corresponding log target.
In the above code, two log targets are registered in [[yii \ log \ Dispatcher: targets.

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

  • [[Yii \ log \ DbTarget]: saves log information to the database.
  • [[Yii \ log \ EmailTarget]: sends the log information to the specified email address. the preceding example is as follows.
  • [[Yii \ log \ FileTarget]: writes logs to files.
  • [[Yii \ log \ SyslogTarget]: Call the syslog () method of PHP to write logs to system logs.

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

Message Filtering
For each log target, you can configure [[yii \ log \ Target: levels | levels] and [[yii \ log \ Target :: categories | categories] sets the severity and category of an attribute class.
[[Yii \ log \ Target: levels | levels] attributes use one or more values in an array. this array contains the following values:

  • Error: message corresponding to [[Yii: error ()]
  • Warning: corresponding to the message recorded in [[Yii: warning ()]
  • Info: information corresponding to the [[Yii: info ()] record
  • Trace: information corresponding to the [[Yii: trace ()] record.
  • Profile: information corresponding to the [[Yii: beginProfile ()] and [[Yii: endProfile ()] records. in this way, more details are recorded below.

If you do not specify the value of [[yii \ log \ Target: levels | levels], information of any level will be recorded.

[[Yii \ log \ Target: categories | categories] the attribute value is an array. The value in this array can be a specific category name, it can also be a regular matching pattern. Only when the target can find the corresponding category name in the array or match a matching pattern can the target process the messages. The matching pattern is composed of a number after the category name. If this category exactly matches the character before the matching pattern number, the corresponding matching value is found for 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 the relevant log information, so they all match the pattern yii \ db *

Similarly, if [[yii \ log \ Target: categories | categories] is not specified, the log information of each category will be processed.
In addition to setting a whitelist by using the [[yii \ log \ Target: categories | categories] attribute, you can also use [yii \ log \ Target :: T | except] attribute to set the category blacklist. The category log information of the blacklist is not processed by the target.

The following configuration specifies that a category matches yii \ db * or yii \ web \ HttpException: *, but does not include a category of yii \ web \ HttpException: 404, besides, it only processes error and warning log information.

['class' => 'yii\log\FileTarget','levels' => ['error', 'warning'],'categories' => [  'yii\db\*',  'yii\web\HttpException:*',],'except' => [  'yii\web\HttpException:404',],]

Note: When the error handle captures an HTTP exception, the recorded log information is in the format of yii \ web \ HttpException: ErrorCode.
Record. for example, [[yii \ web \ NotFoundHttpException] will be recorded as yii \ web \ HttpException: 404
Message formatting
Logs targets are exported in multiple formats. For example, if your log target is [[yii \ log \ FileTarget], when you record the log in your program, it should find a file similar to runtime/log/app. log records the following information:

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 into the following format:

Timestamp [IP address][User ID][Session ID][Severity Level][Category] Message Text

You can configure a custom callback function for the [[yii \ log \ Target: prefix] attribute to customize the log prefix. The following code adds the user ID (IP address, sessionId, and other sensitive information due to personal privacy) to each log ).

['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 prefix of the log message, the log target also attaches some context information to each batch of log records. By default, Global PHP variables include $ _ GET, $ _ POST, $ _ FILES, $ _ COOKIE, $ _ SESSION, and $ _ SERVER. you can configure [[yii \ log \ Target: logVars] to adjust the global variables of log records. The following code records only the variables related to $ _ SERVER.

['class' => 'yii\log\FileTarget','logVars' => ['_SERVER'],]

When 'logvars' is empty, it indicates no relevant context information is recorded. If you want to customize the context information provision method, you can override the [[yii \ log \ Target: getContextMessage ()] method.

Trace level of a message
During the development process, we always expect to know where each log message comes from. In Yii, you can configure the [[yii \ log \ Dispatcher: traceLevel | traceLevel] attribute. The configuration example is as follows:

return ['bootstrap' => ['log'],'components' => [  'log' => [    'traceLevel' => YII_DEBUG ? 3 : 0,    'targets' => [...],  ],],];

In the preceding example, when YII_DEBUG is true, set [[yii \ log \ Dispatcher: traceLevel | traceLevel] to 3, and vice versa. what does this mean? 3 indicates that each log record records the related three-tier stack call information. 0 indicates that no related stack call information is recorded.

Tip: There is no need to always record the call stack information, which is performance-consuming. Therefore, you should only use this function during development or debugging.
Clearing and exporting messages
As mentioned above, the recorded messages are stored in [[yii \ log \ Logger | logger object] in an array. To limit this array to consume too much memory, when the size of the content contained in this array reaches a certain amount, the corresponding target will be transferred from the memory to the corresponding target (file, database ...). You can set the value of [[yii \ log \ Dispatcher: flushInterval | flushInterval] to determine the quantity. As shown below:

return ['bootstrap' => ['log'],'components' => [  'log' => [    'flushInterval' => 100,  // default is 1000    'targets' => [...],  ],],];

Note: The memory will be refreshed when the application stops running, so that the log target can record the complete information.
This action of Flushing log information from memory to the corresponding storage location does not happen immediately. As a matter of fact, it is the same as above that it occurs only when the log size in the memory reaches a certain level. You can configure the [[yii \ log \ target: exportInterval | exportInterval] values of different targets as follows:

['class' => 'yii\log\FileTarget','exportInterval' => 100, // default is 1000]

Because of the settings for clearing and exporting, by default, you will not immediately see the log message under the log target when calling the Yii: trace () or other logging methods. This is a problem for some console programs that run for a long time. However, this problem can be solved. in the following code, you need to set [[yii \ log \ Dispatcher: flushInterval | flushInterval] and [[yii \ log \ Target:: exportInterval | exportInterval] values are set to 1:

return ['bootstrap' => ['log'],'components' => [  'log' => [    'flushInterval' => 1,    'targets' => [      [        'class' => 'yii\log\FileTarget',        'exportInterval' => 1,      ],    ],  ],],];

Note: frequent clearing and exporting of log messages will reduce the system performance.
Switch logs to targets
You can disable the log Target by setting the [[yii \ log \ target: enabled | enabled] attribute. As described in the following code:

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

The above code requires that you have the following configuration in the configuration file:

return ['bootstrap' => ['log'],'components' => [  'log' => [    'targets' => [      'file' => [        'class' => 'yii\log\FileTarget',      ],      'db' => [        'class' => 'yii\log\DbTarget',      ],    ],  ],],];

Create a new target
First, it is easy to create a new log target. The main thing you do is to implement the [[yii \ log \ Target: export ()] method and put the message of the array type [[yii \ log \ Target :: messages] is sent to the specified storage media. In this process, you can call [yii \ log \ Target: formatMessage ()] to format each log message. For more details, you can find detailed information in the Yiid release version.

Performance Evaluation
Performance Evaluation is a special log record. It is usually used to obtain the execution time data of some modules to locate performance problems. For example, the [[yii \ db \ Command] class uses performance evaluation logs to obtain the time spent in each SQL query.

To use this type of log, you must first determine the scope of the code to be tested. Then you should keep each piece of code closed, as shown below:

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

MyBenchmark is only an identifier used for quick locating when you view the corresponding log records.
The beginProfile and endProfile can be nested, but correct close relationships must be ensured, 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 an error occurs in the above closed relationship, the corresponding record will not work normally.

For each piece of evaluated code, the log level is profile. You can configure the information in the target of the log and export it. Yii has built-in Yii debugger to display the evaluation results.

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.