溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

YII Framework框架之日志的示例分析

發(fā)布時間:2021-08-30 14:52:04 來源:億速云 閱讀:125 作者:小新 欄目:開發(fā)技術

小編給大家分享一下YII Framework框架之日志的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

具體如下:

日志的作用(此處省略1000字)

YII中的日志很好很強大,允許你把日志信息存放到數(shù)據(jù)庫,發(fā)送到制定email,存放咋文件中,意見顯示頁面是,甚至可以用來做性能分析。

YII中日志的基本配置:/yii_dev/testwebap/protected/config/main.php

'log'=>array(
  'class'=>'CLogRouter',
  'routes'=>array(
    array(
      'class'=>'CFileLogRoute',
      'levels'=>'error, warning',
    ),
    // uncomment the following to show log messages on web pages
    /*
    array(
      'class'=>'CWebLogRoute',
    ),
    */
  ),
),

YII中日志的基本使用

可以通過YII提供的Yii::log和Yii::trace進行日志信息的輸出,兩者的區(qū)別看看定義就知道了。

函數(shù)定義

public static function trace($msg,$category='application')
{
  if(YII_DEBUG)
    self::log($msg,CLogger::LEVEL_TRACE,$category);
}
public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
{
  if(self::$_logger===null)
    self::$_logger=new CLogger;
  if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  {
    $traces=debug_backtrace();
    $count=0;
    foreach($traces as $trace)
    {
      if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
      {
        $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
        if(++$count>=YII_TRACE_LEVEL)
          break;
      }
    }
  }
  self::$_logger->log($msg,$level,$category);
}

$msg:你要輸出的日志信息

$category:日志信息所屬分類

$level:日志信息的級別:

const LEVEL_TRACE='trace';用于調(diào)試環(huán)境,追蹤程序執(zhí)行流程
const LEVEL_WARNING='warning';警告信息
const LEVEL_ERROR='error';致命錯誤信息
const LEVEL_INFO='info';普通提示信息
const LEVEL_PROFILE='profile';性能調(diào)試信息

基本使用方法舉例

<?php
class DefaultController extends Controller
{
  public function actionCache ()
  {
    $category='system.testmod.defaultController';
    $level=CLogger::LEVEL_INFO;
    $msg='action begin ';
    Yii::log($msg,$level,$category);
  }
}

YII中日志的輸出位置

上文提到YII中日志的輸出位置可以定義為很多位置。主要通過配置文件修改例如:

'log'=>array(
  'class'=>'CLogRouter',
  'routes'=>array(
    array(
      'class'=>'CFileLogRoute',
      'levels'=>'error, warning',
    ),
    // uncomment the following to show log messages on web pages
    array(
      'class'=>'CWebLogRoute',
    ),
  ),
),

不僅輸出到日志文件中,還輸出到web頁面上。

配置文件中:

routes用于配置日志輸出的位置,
class是日志,日志路由的類名
levels是日志的頂級,字符串序列,用都好分割。具體對應CLooger中的常量

注意:

日志文件的存放位置是:/yii_dev/testwebap/protected/runtime/application.log

官方的日志介紹的很詳細,但是后半部分中文翻譯缺失了,這里進行翻譯補全。

Yii 提供了一個靈活可擴展的日志功能。記錄的日志 可以通過日志級別和信息分類進行歸類。通過使用 級別和分類過濾器,所選的信息還可以進一步路由到 不同的目的地,例如一個文件,Email,瀏覽器窗口等。

1. 信息記錄

信息可以通過 Yii::log 或 Yii::trace 記錄。其 區(qū)別是后者只在當應用程序運行在 調(diào)試模式(debug mode) 中時才會記錄信息。

Yii::log($message, $level, $category);
Yii::trace($message, $category);

當記錄信息時,我們需要指定它的分類和級別 分類是一段格式類似于 路徑別名 的字符串。 例如,如果一條信息是在 CController 中記錄的,我們可以使用 system.web.CController 作為分類。信息級別應該是下列值中的一種:

trace: 這是在 Yii::trace 中使用的級別。它用于在開發(fā)中 跟蹤程序的執(zhí)行流程。
info: 這個用于記錄普通的信息。
profile: 這個是性能概述(profile)。下面馬上會有更詳細的說明。
warning: 這個用于警告(warning)信息。
error: 這個用于致命錯誤(fatal error)信息。

2. 信息路由

通過 Yii::log 或 Yii::trace 記錄的信息是保存在內(nèi)存中的。 我們通常需要將它們顯示到瀏覽器窗口中,或者將他們保存到一些 持久存儲例如文件、Email中。這個就叫作 信息路由,例如, 發(fā)送信息到不同的目的地。

在 Yii 中,信息路由是由一個叫做 CLogRouter 的應用組件管理的。 它負責管理一系列稱作 日志路由 的東西。每個日志路由 代表一個單獨的日志目的地。通過一個日志路由發(fā)送的信息會被他們的級別和分類過濾。

要使用信息路由,我們需要安裝并預加載一個 CLogRouter 應用組件。我們也還需要配置它的 routes 屬性為我們想要的那些日志路由。 下面的代碼演示了一個所需的 應用配置 示例:

array(
  ......
  'preload'=>array('log'),
  'components'=>array(
    ......
    'log'=>array(
      'class'=>'CLogRouter',
      'routes'=>array(
        array(
          'class'=>'CFileLogRoute',
          'levels'=>'trace, info',
          'categories'=>'system.*',
        ),
        array(
          'class'=>'CEmailLogRoute',
          'levels'=>'error, warning',
          'emails'=>'admin@example.com',
        ),
      ),
    ),
  ),
)

在上面的例子中,我們定義了兩個日志路由。第一個是 CFileLogRoute ,它會把信息保存在位于應用程序 runtime 目錄中的一個文件中。 而且只有級別為 trace 或 info 、分類以 system. 開頭的信息才會被保存。 第二個路由是 CEmailLogRoute ,它會將信息發(fā)送到指定的 email 地址,且只有級別為 error 或 warning 的才會發(fā)送。

在 Yii 中,有下列幾種日志路由可用:

CDbLogRoute: 將信息保存到數(shù)據(jù)庫的表中。
CEmailLogRoute: 發(fā)送信息到指定的 Email 地址。
CFileLogRoute: 保存信息到應用程序 runtime 目錄中的一個文件中。
CWebLogRoute: 將 信息 顯示在當前頁面的底部。
CProfileLogRoute: 在頁面的底部顯示概述(profiling)信息。

信息: 信息路由發(fā)生在當前請求周期最后的 onEndRequest 事件觸發(fā)時。 要顯式終止當前請求過程,請調(diào)用 CApplication::end() 而不是使用 die() 或 exit(),因為 CApplication::end() 將會觸發(fā)onEndRequest 事件, 這樣信息才會被順利地記錄。

3. 信息過濾

正如我們所提到的,信息可以在他們被發(fā)送到一個日志路由之前通過它們的級別和分類過濾。 這是通過設置對應日志路由的 levels 和 categories 屬性完成的。 多個級別或分類應使用逗號連接。

由于信息分類是類似 xxx.yyy.zzz 格式的,我們可以將其視為一個分類層級。 具體地,我們說 xxx 是 xxx.yyy的父級,而xxx.yyy 又是 xxx.yyy.zzz 的父級。 這樣我們就可以使用 xxx.* 表示分類 xxx 及其所有的子級和孫級分類

4. 記錄上下文信息

從版本 1.0.6 起,我們可以設置記錄附加的上下文信息, 比如 PHP 的預定義變量(例如 $_GET, $_SERVER),session ID,用戶名等。 這是通過指定一個日志路由的 CLogRoute::filter屬性為一個合適的日志過濾規(guī)則實現(xiàn)的。

The framework comes with the convenient CLogFilter that may be used as the needed log filter in most cases. By default, CLogFilter will log a message with variables like $_GET, $_SERVER which often contains valuable system context information. CLogFilter can also be configured to prefix each logged message with session ID, username, etc., which may greatly simplifying the global search when we are checking the numerous logged messages.

框架可能在許多數(shù)情況下會用到日志過濾器CLogFilter來過濾日志。默認情況下,CLogFilter日志消息包含了許多系統(tǒng)上下文信息的變量,像$ _GET,$_SERVER。 CLogFilter也可以配置的前綴與會話ID,用戶名等,我們在檢查無數(shù)記錄的消息每個記錄的消息時,這可能會極大地簡化了搜索難度

The following configuration shows how to enable logging context information. Note that each log route may have its own log filter. And by default, a log route does not have a log filter.

下面的配置顯示了如何啟用日志記錄的上下文信息。請注意,每個日志路由可能有其自己的日志過濾器。 默認情況下,日志路由不會有日志篩選器。

array(
  ......
  'preload'=>array('log'),
  'components'=>array(
    ......
    'log'=>array(
      'class'=>'CLogRouter',
      'routes'=>array(
        array(
          'class'=>'CFileLogRoute',
          'levels'=>'error',
          'filter'=>'CLogFilter',
        ),
        ...other log routes...
      ),
    ),
  ),
)

Starting from version 1.0.7, Yii supports logging call stack information in the messages that are logged by calling Yii::trace. This feature is disabled by default because it lowers performance. To use this feature, simply define a constant named YII_TRACE_LEVEL at the beginning of the entry script (before includingyii.php) to be an integer greater than 0. Yii will then append to every trace message with the file name and line number of the call stacks belonging to application code. The number YII_TRACE_LEVEL determines how many layers of each call stack should be recorded. This information is particularly useful during development stage as it can help us identify the places that trigger the trace messages.

從版本1.0.7開始,Yii的日志記錄可以采用堆棧的方式記錄消息,此功能默認是關閉的,因為它會降低性能。要使用此功能,只需在入口腳本(前includingyii.php)定義一個命名為YII_TRACE_LEVEL的常量即一個大于0的整數(shù)。 Yii將在堆棧信息中追加應用程序要到的每一個文件名和行號??梢酝ㄟ^設置YII_TRACE_LEVEL來設定堆棧的層數(shù)。這種方式在開發(fā)階段特別有用,因為它可以幫助我們確定觸發(fā)跟蹤消息的地方。

5. Performance Profiling 性能分析

Performance profiling is a special type of message logging. Performance profiling can be used to measure the time needed for the specified code blocks and find out what the performance bottleneck is.

性能分析是一類特殊類型的消息記錄。性能分析可用于測量指定代碼塊所需的時間,并找出性能瓶頸是什么。

To use performance profiling, we need to identify which code blocks need to be profiled. We mark the beginning and the end of each code block by inserting the following methods:

要使用性能分析日志,我們需要確定哪些代碼塊需要分析。我們要在分析性能的代碼短的開始和結尾添加如下方法:

Yii::beginProfile('blockID');
...code block being profiled...
Yii::endProfile('blockID');

where blockID is an ID that uniquely identifies the code block.

其中blockID是一個標識代碼塊的唯一ID。

Note, code blocks need to be nested properly. That is, a code block cannot intersect with another. It must be either at a parallel level or be completely enclosed by the other code block.

注意,這些方法不能交叉嵌套

To show profiling result, we need to install a CLogRouter application component with a CProfileLogRoute log route. This is the same as we do with normal message routing. The CProfileLogRoute route will display the performance results at the end of the current page.

為了顯示分析結果,我們需要為CLogRouter增加CProfileLogRoute路由。然后通過CProfileLogRoute可以把性能測試結果顯示在當前頁面結束。

6. Profiling SQL Executions 分析SQL執(zhí)行

Profiling is especially useful when working with database since SQL executions are often the main performance bottleneck of an application. While we can manually insert beginProfile and endProfilestatements at appropriate places to measure the time spent in each SQL execution, starting from version 1.0.6, Yii provides a more systematic approach to solve this problem.

在數(shù)據(jù)庫開發(fā)中分析是特別有用的,因為SQL執(zhí)行往往是應用程序的主要性能瓶頸。盡管我們可以手動在每個SQL執(zhí)行的適當?shù)牡胤讲迦隻eginProfile和endProfile來衡量花費的時間,但從1.0.6版本開始,Yii提供了更系統(tǒng)的方法來解決這個問題。

By setting CDbConnection::enableProfiling to be true in the application configuration, every SQL statement being executed will be profiled. The results can be readily displayed using the aforementionedCProfileLogRoute, which can show us how much time is spent in executing what SQL statement. We can also call CDbConnection::getStats() to retrieve the total number SQL statements executed and their total execution time.

再實際的應用程序當中通過設置CDbConnection::enableProfiling愛分析每一個正在執(zhí)行的SQL語句。使用 CProfileLogRoute,結果可以很容易地顯示。它可以顯示我們是在執(zhí)行什么SQL語句花費多少時間。我們也可以調(diào)用CDbConnection:getStats()來分析檢索SQL語句的執(zhí)行總數(shù)和其總的執(zhí)行時間。

以上是“YII Framework框架之日志的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI