Google News
logo
Yii framework - Interview Questions
What about Logging in Yii Framework?
Yii provides a powerful logging framework that is highly customizable and extensible. Using this framework, you can easily log various types of messages, filter them, and gather them at different targets, such as files, databases, emails.
 
Using the Yii logging framework involves the following steps :
 
* Record log messages at various places in your code;
* Configure log targets in the application configuration to filter and export log messages;
* Examine the filtered logged messages exported by different targets (e.g. the Yii debugger).

In this section, we will mainly describe the first two steps.
 
Log Messages : Recording log messages is as simple as calling one of the following logging methods :
 
Yii::debug() : record a message to trace how a piece of code runs. This is mainly for development use.
Yii::info() : record a message that conveys some useful information.
Yii::warning() : record a warning message that indicates something unexpected has happened.
Yii::error() : record a fatal error that should be investigated as soon as possible.

These logging methods record log messages at various severity levels and categories. They share the same function signature function ($message, $category = 'application'), where $message stands for the log message to be recorded, while $category is the category of the log message. The code in the following example records a trace message under the default category application:
Yii::debug('start calculating average revenue');
Info : Log messages can be strings as well as complex data, such as arrays or objects. It is the responsibility of log targets to properly deal with log messages. By default, if a log message is not a string, it will be exported as a string by calling yii\helpers\VarDumper::export().
 
To better organize and filter log messages, it is recommended that you specify an appropriate category for each log message. You may choose a hierarchical naming scheme for categories, which will make it easier for log targets to filter messages based on their categories. A simple yet effective naming scheme is to use the PHP magic constant __METHOD__ for the category names. This is also the approach used in the core Yii framework code. For example : 
Yii::debug('start calculating average revenue', __METHOD__);
The __METHOD__ constant evaluates as the name of the method (prefixed with the fully qualified class name) where the constant appears. For example, it is equal to the string 'app\controllers\RevenueController::calculate' if the above line of code is called within this method.
 
Info : The logging methods described above are actually shortcuts to the log() method of the logger object which is a singleton accessible through the expression Yii::getLogger(). When enough messages are logged or when the application ends, the logger object will call a message dispatcher to send recorded log messages to the registered log targets.
 
Log Targets : A log target is an instance of the yii\log\Target class or its child class. It filters the log messages by their severity levels and categories and then exports them to some medium. For example, a database target exports the filtered log messages to a database table, while an email target exports the log messages to specified email addresses.
 
You can register multiple log targets in an application by configuring them through the log application component in the application configuration, like the following :
return [
    // the "log" component must be loaded during bootstrapping time
    'bootstrap' => ['log'],
    // the "log" component process messages with timestamp. Set PHP timezone to create correct timestamp
    'timeZone' => 'America/Los_Angeles',
    '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 loaded during bootstrapping time so that it can dispatch log messages to targets promptly. That is why it is listed in the bootstrap array as shown above.
 
In the above code, two log targets are registered in the yii\log\Dispatcher::$targets property :
 
the first target selects error and warning messages and saves them in a database table;

the second target selects error messages under the categories whose names start with yii\db\, and sends them in an email to both admin@example.com and developer@example.com.

Yii comes with the following built-in log targets. Please refer to the API documentation about these classes to learn how to configure and use them.
 
yii\log\DbTarget : stores log messages in a database table.
yii\log\EmailTarget : sends log messages to pre-specified email addresses.
yii\log\FileTarget : saves log messages in files.
yii\log\SyslogTarget : saves log messages to syslog by calling the PHP function syslog().
Advertisement