CakePHP - 日誌記錄



在 CakePHP 中進行日誌記錄非常簡單。您只需使用一個函式即可。您可以記錄錯誤、異常、使用者活動、使用者採取的操作,以及任何後臺程序(如 cron 作業)。在 CakePHP 中記錄資料很容易。Log() 函式由 LogTrait 提供,它是幾乎所有 CakePHP 類的共同祖先。

日誌記錄配置

我們可以在檔案config/app.php中配置日誌。該檔案有一個日誌部分,您可以在其中配置日誌記錄選項,如下面的螢幕截圖所示。

Programming

預設情況下,您會看到兩個日誌級別 - errordebug 已為您配置。每個級別將處理不同級別的訊息。

CakePHP 支援各種日誌記錄級別,如下所示:

  • Emergency - 系統無法使用

  • Alert - 必須立即採取行動

  • Critical - 嚴重情況

  • Error - 錯誤情況

  • Warning - 警告情況

  • Notice - 正常但重要的條件

  • Info - 資訊性訊息

  • Debug - 除錯級別訊息

寫入日誌檔案

我們可以透過兩種方式寫入日誌檔案。

第一種是使用靜態write()方法。以下是靜態write()方法的語法。

語法 write( integer|string $level, mixed $message, string|array $context [] )
引數

正在寫入的訊息的嚴重性級別。該值必須是整數或與已知級別匹配的字串。

要記錄的訊息內容。

用於記錄訊息的其他資料。可以傳遞特殊的 scope 金鑰以用於進一步過濾要使用的日誌引擎。如果傳遞字串或數字索引陣列,則將被視為 scope 金鑰。有關日誌範圍的更多資訊,請參閱Cake\Log\Log::config()

返回值

布林值

描述

將給定的訊息和型別寫入所有已配置的日誌介面卡。已配置的介面卡同時傳遞 $level 和 $message 變數。$level 是以下字串/值之一。

第二種是使用任何使用LogTraitlog()快捷方式函式。呼叫 log() 將在內部呼叫Log::write() -

示例

按照以下程式對config/routes.php檔案進行更改。

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',
      ['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('logex',['controller'=>'Logexs','action'=>'index']);
   $builder->fallbacks();
});

src/Controller/LogexsController.php處建立一個LogexsController.php檔案。將以下程式碼複製到控制器檔案中。

src/Controller/LogexsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Log\Log;
   class LogexsController extends AppController{
      public function index(){
         /*The first way to write to log file.*/
         Log::write('debug',"Something didn't work.");
         /*The second way to write to log file.*/
         $this->log("Something didn't work.",'debug');
      }
   }
?>

src/Template處建立一個目錄Logexs,並在該目錄下建立一個名為 index.php 的View檔案。將以下程式碼複製到該檔案中。

src/Template/Logexs/index.php

Something is written in log file. Check log file logs\debug.log

透過訪問以下 URL 執行上述示例。

https:///cakephp4/logex

輸出

執行後,您將收到以下輸出。

Debugs

日誌將新增到 log/debug.log 檔案中 -

Logfile
廣告

© . All rights reserved.