程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> YII Framework框架教程之日志用法詳解

YII Framework框架教程之日志用法詳解

編輯:PHP綜合

本文實例講述了YII Framework框架日志用法。分享給大家供大家參考,具體如下:

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

YII中的日志很好很強大,允許你把日志信息存放到數據庫,發送到制定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進行日志信息的輸出,兩者的區別看看定義就知道了。

函數定義

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';用於調試環境,追蹤程序執行流程
const LEVEL_WARNING='warning';警告信息
const LEVEL_ERROR='error';致命錯誤信息
const LEVEL_INFO='info';普通提示信息
const LEVEL_PROFILE='profile';性能調試信息

基本使用方法舉例

<?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 記錄。其 區別是後者只在當應用程序運行在 調試模式(debug mode) 中時才會記錄信息。

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

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

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

2. 信息路由

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

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

要使用信息路由,我們需要安裝並預加載一個 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'=>'[email protected]',
        ),
      ),
    ),
  ),
)

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

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

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

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

3. 信息過濾

正如我們所提到的,信息可以在他們被發送到一個日志路由之前通過它們的級別和分類過濾。 這是通過設置對應日志路由的 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屬性為一個合適的日志過濾規則實現的。

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.

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

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的整數。 Yii將在堆棧信息中追加應用程序要到的每一個文件名和行號。可以通過設置YII_TRACE_LEVEL來設定堆棧的層數。這種方式在開發階段特別有用,因為它可以幫助我們確定觸發跟蹤消息的地方。

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執行

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.

在數據庫開發中分析是特別有用的,因為SQL執行往往是應用程序的主要性能瓶頸。盡管我們可以手動在每個SQL執行的適當的地方插入beginProfile和endProfile來衡量花費的時間,但從1.0.6版本開始,Yii提供了更系統的方法來解決這個問題。

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愛分析每一個正在執行的SQL語句。使用 CProfileLogRoute,結果可以很容易地顯示。它可以顯示我們是在執行什麼SQL語句花費多少時間。我們也可以調用CDbConnection:getStats()來分析檢索SQL語句的執行總數和其總的執行時間。

更多關於Yii相關內容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結》、《php優秀開發框架總結》、《smarty模板入門基礎教程》、《php日期與時間用法總結》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》

希望本文所述對大家基於Yii框架的PHP程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved