Yii - 日誌記錄



Yii 提供了一個高度可定製和可擴充套件的框架。藉助此框架,您可以輕鬆記錄各種型別的訊息。

要記錄訊息,您應該呼叫以下方法之一:

  • Yii::error() − 記錄致命錯誤訊息。

  • Yii::warning() − 記錄警告訊息。

  • Yii::info() − 記錄包含一些有用資訊的文字。

  • Yii::trace() − 記錄訊息以跟蹤程式碼片段的執行方式。

以上方法在不同的類別中記錄日誌訊息。它們共享以下函式簽名:

function ($message, $category = 'application')

其中:

  • $message − 要記錄的日誌訊息

  • $category − 日誌訊息的類別

一種簡單方便的命名方案是使用 PHP 的 `__METHOD__` 魔術常量。例如:

Yii::info('this is a log message', __METHOD__);

日誌目標是 yii\log\Target 類的例項。它按類別過濾所有日誌訊息,並將它們匯出到檔案、資料庫和/或電子郵件。

步驟 1 − 您也可以註冊多個日誌目標,例如:

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',
               ],
            ],
         ],
      ],
   ],
];

在上面的程式碼中,註冊了兩個目標。第一個目標選擇所有錯誤、警告、跟蹤和資訊訊息,並將它們儲存到資料庫中。第二個目標將所有錯誤和警告訊息傳送到管理員電子郵件。

Yii 提供以下內建日誌目標:

  • yii\log\DbTarget − 將日誌訊息儲存在資料庫中。

  • yii\log\FileTarget − 將日誌訊息儲存到檔案中。

  • yii\log\EmailTarget − 將日誌訊息傳送到預定義的電子郵件地址。

  • yii\log\SyslogTarget − 透過呼叫 PHP 函式 syslog() 將日誌訊息儲存到 syslog。

預設情況下,日誌訊息的格式如下:

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

步驟 2 − 要自定義此格式,您應該配置 yii\log\Target::$prefix 屬性。例如:

[
   '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]";
   }
]

上面的程式碼片段將日誌目標配置為在所有日誌訊息前加上當前使用者 ID。

預設情況下,日誌訊息包括來自以下全域性 PHP 變數的值:`$_GET`、`$_POST`、`$_SESSION`、`$_COOKIE`、`$_FILES` 和 `$_SERVER`。要修改此行為,您應該使用要包含的變數名稱配置 yii\log\Target::$logVars 屬性。

所有日誌訊息都由日誌記錄器物件儲存在一個數組中。日誌記錄器物件每次陣列累積一定數量的訊息(預設為 1000)時,都會將記錄的訊息重新整理到日誌目標。

步驟 3 − 要自定義此數字,您應該呼叫 flushInterval 屬性

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

即使日誌記錄器物件將日誌訊息重新整理到日誌目標,它們也不會立即匯出。匯出發生在日誌目標累積一定數量的訊息(預設為 1000)時。

步驟 4 − 要自定義此數字,您應該配置 exportInterval 屬性。

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

步驟 5 − 現在,修改 config/web.php 檔案:

<?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;
?>

在上面的程式碼中,我們定義了日誌應用程式元件,將 flushIntervalexportInteval 屬性設定為 1,以便所有日誌訊息都立即出現在日誌檔案中。我們還省略了日誌目標的 levels 屬性。這意味著所有類別的日誌訊息(錯誤、警告、資訊、跟蹤)都將出現在日誌檔案中。

步驟 6 − 然後,在 SiteController 中建立一個名為 actionLog() 的函式。

public function actionLog() {
   Yii::trace('trace log message');
   Yii::info('info log message');
   Yii::warning('warning log message');
   Yii::error('error log message');
}

在上面的程式碼中,我們只是將四個不同類別的日誌訊息寫入日誌檔案。

步驟 7 − 在 Web 瀏覽器的位址列中鍵入 URL https://:8080/index.php?r=site/log。日誌訊息應該出現在應用程式的 app/runtime/logs 目錄下的 app.log 檔案中。

Action Log Function
廣告
© . All rights reserved.