Common Log Operations Summary _php tips for the yii framework of PHP

Source: Internet
Author: User
Tags session id system log yii

Yii provides a highly customizable and highly scalable log framework. Depending on the usage scenario, you can easily record, filter, and merge messages on a variety of lines, such as text files, database files, and mail.

The log framework using YII consists of the following steps:

Method of calling Logging

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

Logging is simply a simple way to invoke the following:

    • [[Yii::trace ()]]: Records related messages about a piece of code running. Mainly for the development environment.
    • [[Yii::info ()]]: used when some of the more useful information is recorded in certain locations.
    • [[Yii::warning ()]]: Use this method when something outside of the expectation occurs.
    • [[Yii::error ()]]: Call this method to record the relevant information when a fatal problem that needs to be resolved immediately occurs.

Although the above methods record information according to different level and type, they actually invoke the same method function ($message, $category = ' application '). Where $message is the information to be recorded, $category represents the attribution class for this log. The following code indicates that a trace type of information is logged under the default ' Application ' category.

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

Hint: The $message can be a simple string or a complex array, object. You should choose the appropriate $message type according to the responsibilities of the log records in different scenarios. By default, if you record a $message that is not a string, the log will invoke the [[Yii\helpers\vardumper::export ()]] method to output a string message when it is exported.

For better organization management and filtering of log messages, it is usually appropriate to assign a suitable category to each log. You can choose a classification that has a distinct level of meaning to facilitate the screening of different categories of journals based on different purposes. A simple and efficient way to name a class is to use the magic constant method of PHP as a taxonomy. The core code in the YII framework is doing this when logging. For example:

Yii::trace (' Start calculating average revenue ', __method__);

Where a constant method appears, it represents the name of the current method (plus the full prefix of the class to which the current methods belong). For example, if you have that line of code in the Calculate method inside the App\controllers\revenuecontroller class, then this means ' app\controllers\ Revenuecontroller::calculate '.

Hint: The method described above is in fact simply a simple use of the [[Yii\log\logger::log () |log ()] method of a single instance [[Yii\log\logger|logger Object]], which we can do through Yii::getlogger () method to obtain this single Instance object. When we have logged enough log information or the current application run is over, the log object will invoke the [Yii\log\dispatcher|message Dispatcher] method to write the logged information to the configured destination.

Log targets
A log Target is an instance of [[Yii\log\target]] or a subclass of it. It filters the logs according to the severity of class and classification, and then exports the logs to the appropriate media. For example, a [[Yii\log\dbtarget|database target]] object will export the filtered log information to the corresponding database.
You can register multiple log targets in the log component of the application's configuration file, as follows:

return [
///the "log" component must is loaded during bootstrapping time
' Bootstrap ' => [' log '],

' component S ' => ['
  log ' => [' Targets ' => ['
        class ' => '
        yii\log\dbtarget ', ' Levels ' => '] Error ', ' warning '],
        ' class ' => ' Yii\log\emailtarget ', '
        levels ' => [' Error '],
        ' Categories ' => [' yii\db\* '],
        ' message ' => ['
          from ' => [' '],
          ' to ' => [' ', ' '],
          ' subject ' => ' Database errors at ',

Note: The log component must be configured in bootstrap to distribute log information to the corresponding log target.
In the code above, two log target is registered in [[Yii\log\dispatcher::targets]].

The first filters out error and warning messages and saves the information to the database.
The second filters out the error message that starts with yii\db* and sends the message to and
Yii has the following built-in log targets, you can refer to the API documentation to learn how to configure and use them specifically.

    • [[Yii\log\dbtarget]]: Save the log information to the database.
    • [[Yii\log\emailtarget]]: Send the log information to the specified mailbox, the example above is.
    • [[Yii\log\filetarget]]: Write the log to the file.
    • [[Yii\log\syslogtarget]]: invokes the Syslog () method of PHP to write logs to the system log.

Next, let's take a look at the functionality that common log target has.

Message filtering
for each of the log Target, you can configure its [[Yii\log\target::levels|levels]] and [[Yii\log\target::categories|categories]] The attribute class sets its severity and the classification of its attribution.
The [[Yii\log\target::levels|levels]] property takes one or more values from an array that contains the following values:

    • Error: Messages that correspond to [[Yii::error ()]] Records
    • Warning: Messages that correspond to [[Yii::warning ()]] Records
    • Info: Information that corresponds to [[Yii::info ()]] Records
    • Trace: Information that corresponds to the [[Yii::trace ()]] record.
    • Profile: The information that corresponds to [[Yii::beginprofile ()]] and [[Yii::endprofile ()]] is recorded, and more details are recorded under this method.

If you do not specify a value for [[Yii\log\target::levels|levels]], then any level information will be recorded.

The value of the [[Yii\log\target::categories|categories]] property is an array, and the value in the array can be a specific category name or a matching pattern similar to a regular one. Only if Target can find the corresponding category name in the array or match a matching pattern, he will process the message. The matching pattern here is composed of a number appended to the name of the category. If the classification matches exactly the character before the number of the matching pattern, then this category finds the corresponding matching value. For example, in the class [[Yii\db\command]], the Yii\db\command::execute and Yii \db\command:: The Query method uses the class name class to record the relevant log information, then they all match the pattern yii\db*

Similarly, if we do not specify [[Yii\log\target::categories|categories]], then the log information for each category will be processed.
In addition to setting the white list of categories through the [[yii\log\target::categories|categories]] attribute, you can also set a blacklist of categories through the [[Yii\log\target::except|except]] property. Classified log information belonging to the blacklist is not processed by target.

The following configuration specifies a category matching yii\db* or yii\web\httpexception:*, but does not include the yii\web\httpexception:404 classification, and it only handles 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 wrong handle catches an HTTP exception, the logged log information is in Yii\web\httpexception:errorcode format
Records, such as [[Yii\web\notfoundhttpexception]], are recorded as yii\web\httpexception:404
Message formatting
log targets export logs in multiple formats. For example, if your log target is [[Yii\log\filetarget]], you should find the following information similar to the file Runtime/log/app.log record when logging in your program:
2014-10-04 18:10:15 [:: 1][][-][trace][yii\base\module::getmodule] Loading Module:debug

By default, [[Yii\log\target::formatmessage ()]]: It will help us format the log information in the following format:

Timestamp [IP address][user id][session id][severity level][category] Message Text

You can customize the prefix of the log by configuring a custom callback function for the [[Yii\log\target::p Refix] property. The following code implements the user's ID (IP address, SessionID, and other sensitive information) before each log message because the privacy is removed.

' 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, target of the log also attaches some contextual information to each batch of log records. By default, global PHP variables include $_get, $_post, $_files, $_cookie, $_session, and $_server. You can adjust the global variables of the log record by configuring [[Yii\log\target::logvars]]. The following code represents a variable that records only $_server-related variables.

' class ' => ' Yii\log\filetarget ', '
logvars ' => [' _server '],

When ' Logvars ' is empty, the related context information is not logged. If you want to customize the way the context information is provided, you can override the [[Yii\log\target::getcontextmessage ()]] method.

Trace level of message
in the process of development, we always expect to know where each log message comes from. In Yii you can implement by configuring the [[Yii\log\dispatcher::tracelevel|tracelevel]] property. Examples of configurations are as follows:

return [
' Bootstrap ' => [' log '],
' components ' => [
  ' log ' => [
    ' TraceLevel ' =>] yii_debug? 3: 0,
    ' targets ' => [...],],]

The above example sets [[Yii\log\dispatcher::tracelevel|tracelevel]] to 3 when Yii_debug is true, and vice versa to 0. What does that mean? 3 means that each log record records the three stack call information associated with it, and 0 indicates that no related stack call information is logged

Hint: it is not necessary to always record the stack information of the call, which is more performance-consuming. Therefore, you should only use this feature when you are developing or for debugging purposes.
Purge and export of messages
As mentioned above, the recorded message is stored in the form of an array in [[Yii\log\logger|logger Object]]. In order to limit the amount of memory that the array consumes, the corresponding target is transferred from memory to the corresponding destination (file, database ...) when the size of the array contains a certain quantity of content. In You can determine the size of a quantity by setting the value of [[Yii\log\dispatcher::flushinterval|flushinterval]]. Like the following:

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

Note: The memory is refreshed at the end of the application run so that the target of the log can record the complete information.
The movement of log information from memory to the place where it is stored is not immediately occurring. In fact, as with the above, it happens when the log size in memory reaches a certain level. You can do this by configuring different Target [[Yii\log\target::exportinterval|exportinterval]] values for the purpose of the modification, as in the following example:

' class ' => ' Yii\log\filetarget ', '
exportinterval ' =>,//default is 1000

Because of the purge and export settings, by default you call Yii::trace () or other logging methods without immediately seeing log messages in the log target. This is a problem for some long-running console programs. But this problem can be solved by way of the following code, you need to put [[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: Emptying and exporting log messages so frequently can degrade system performance.
targets of the switch log
You can disable Target for the log by setting the [[Yii\log\target::enabled|enabled]] property. As described in the following code:

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

The code above requires you to have one of the following configurations 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 send the array type of message [[Yii\log\target::messages]] to the specified storage medium. In this process you can invoke the [[Yii\log\target::formatmessage ()]] method to format each log message. For more details, you can find detailed information in the YIID release.

Performance evaluation
performance evaluation is a relatively special kind of logging. It is often used to get data on the execution time of some modules to find the problem of performance. For example, [[Yii\db\command]] This class uses the performance evaluation log to get the time it takes for each SQL query.

To use this type of log, the first thing you need to do is determine the scope of the code you want to test. Then you should keep them closed between each piece of code, just like the following:

\yii::beginprofile (' Mybenchmark ');
... code block being profiled
... \yii::endprofile (' Mybenchmark ');

Mybenchmark is just a logo that you can use to quickly locate the corresponding log record.
The Beginprofile and endprofile can be nested again, but the correct closing relationship must be ensured, as follows:

\yii::beginprofile (' Block1 ');

Some code to be profiled

\yii::beginprofile (' Block2 ');
  Some other code to be profiled
\yii::endprofile (' Block2 ');

\yii::endprofile (' Block1 ');

If the closing relationship above is wrong, the corresponding record will not work properly.

For each piece of code being evaluated, the level of the log is profile. You can configure this information in the log's target and export them. Yii Debugger is built into YII to showcase the results of the evaluation.

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: 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.