Yii - Logging

Yii provides a highly customizable and extensible framework. With the help of this framework, you can easily log various types of messages.
To log a message, you should call one of the following methods −
Yii::error() − Records a fatal error message.
Yii::error() − Records a fatal error message.
Yii::warning() − Records a warning message.
Yii::warning() − Records a warning message.
Yii::info() − Records a message with some useful information.
Yii::info() − Records a message with some useful information.
Yii::trace() − Records a message to trace how a piece of code runs.
Yii::trace() − Records a message to trace how a piece of code runs.
The above methods record log messages at various categories. They share the following function signature −
function ($message, $category = 'application')

where −
$message − The log message to be recorded
$message − The log message to be recorded
$category − The category of the log message
$category − The category of the log message
A simple and convenient way of naming scheme is using the PHP __METHOD__ magic constant. For example −
Yii::info('this is a log message', __METHOD__);
A log target is an instance of the yii\log\Target class. It filters all log messages by categories and exports them to file, database, and/or email.
Step 1 − You can register multiple log target as well, like.
return [
   // the "log" component is loaded during bootstrapping time
   'bootstrap' => ['log'],
   'components' => [
      'log' => [
         'targets' => [
            [
               'class' => 'yii\log\DbTarget',
               'levels' => ['error', 'warning', 'trace', 'info'],
            ],
            [
               'class' => 'yii\log\EmailTarget',
               'levels' => ['error', 'warning'],
               'categories' => ['yii\db\*'],
               'message' => [
                  'from' => ['log@mydomain.com'],
                  'to' => ['admin@mydomain.com', 'developer@mydomain.com'],
                  'subject' => 'Application errors at mydomain.com',
               ],
            ],
         ],
      ],
   ],
];
In the code above, two targets are registered. The first target selects all errors, warnings, traces, and info messages and saves them in a database. The second target sends all error and warning messages to the admin email.
Yii provides the following built-in log targets −
yii\log\DbTarget − Stores log messages in a database.
yii\log\DbTarget − Stores log messages in a database.
yii\log\FileTarget − Saves log messages in files.
yii\log\FileTarget − Saves log messages in files.
yii\log\EmailTarget − Sends log messages to predefined email addresses.
yii\log\EmailTarget − Sends log messages to predefined email addresses.
yii\log\SyslogTarget − Saves log messages to syslog by calling the PHP
function syslog().
yii\log\SyslogTarget − Saves log messages to syslog by calling the PHP
function syslog().
By default, log messages are formatted as follows −
Timestamp [IP address][User ID][Session ID][Severity Level][Category] Message Text

Step 2 − To customize this format, you should configure the yii\log\Target::$prefix property. For example.
[
   'class' => 'yii\log\FileTarget',
   'prefix' => function ($message) {
      $user = Yii::$app->has('user', true) ? Yii::$app->get('user') :
      'undefined user';
      $userID = $user ? $user->getId(false) : 'anonym';
      return "[$userID]";
   }
]
The above code snippet configures a log target to prefix all log messages with the current userID.
By default, log messages include the values from these global PHP variables: $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, and $_SERVER. To modify this behavior, you should configure the yii\log\Target::$logVars property with the names of variables that you want to include.
All log messages are maintained in an array by the logger object. The logger object flushed the recorded messages to the log targets each time the array accumulates a certain number of messages(default is 1000).
Step 3 − To customize this number, you should call the flushInterval property.
return [
   'bootstrap' => ['log'],
   'components' => [
      'log' => [
         'flushInterval' => 50, // default is 1000
         'targets' => [...],
      ],
   ],
];
Even when the logger object flushes log messages to log targets, they do not get exported immediately. The export occurs when a log target accumulates a certain number of messages(default is 1000).
Step 4 − To customize this number, you should configure the exportInterval property.
[
   'class' => 'yii\log\FileTarget',
   'exportInterval' => 50, // default is 1000
]
Step 5 − Now, modify the config/web.php file this way.
<?php
   $params = require(__DIR__ . '/params.php');
   $config = [
      'id' => 'basic',
      'basePath' => dirname(__DIR__),
      'bootstrap' => ['log'],
      'components' => [
         'request' => [
            // !!! insert a secret key in the following (if it is empty) - this
               //is required by cookie validation
            'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
         ],
         'cache' => [
            'class' => 'yii\caching\FileCache',
         ],
         'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
         ],
         'errorHandler' => [
            'errorAction' => 'site/error',
         ],
         'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
         ],
         'log' => [
            'flushInterval' => 1,
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
               [
                  'class' => 'yii\log\FileTarget',
                  'exportInterval' => 1,
                  'logVars' => []
               ],
            ],
         ],
         'db' => require(__DIR__ . '/db.php'),
      ],
      'modules' => [
         'hello' => [
            'class' => 'app\modules\hello\Hello',
         ],
      ],
      'params' => $params,
   ];
   if (YII_ENV_DEV) {
      // configuration adjustments for 'dev' environment
      $config['bootstrap'][] = 'debug';
      $config['modules']['debug'] = [
         'class' => 'yii\debug\Module',
      ];
      $config['bootstrap'][] = 'gii';
      $config['modules']['gii'] = [
         'class' => 'yii\gii\Module',
      ];
   }
   return $config;
?>
In the above code, we define the log application component, set the flushInterval and exportInteval properties to 1 so that all log messages appear in the log files immediately. We also omit the levels property of the log target. It means that log messages of all categories(error, warning, info, trace) will appear in the log files.
Step 6 − Then, create a function called actionLog() in the SiteController.
public function actionLog() {
   Yii::trace('trace log message');
   Yii::info('info log message');
   Yii::warning('warning log message');
   Yii::error('error log message');
}
In the above code, we just write four log messages of different categories to the log files.
Step 7 − Type the URL http://localhost:8080/index.php?r=site/log in the address bar of the web browser. Log messages should appear under the app/runtime/logs directory in the app.log file.
 Print
 Add Notes
 Bookmark this page