本文執行個體講述了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';效能調試資訊
基本使用方法舉例
<?phpclass 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'=>'admin@example.com', ), ), ), ),)
在上面的例子中,我們定義了兩個日誌路由。第一個是 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程式設計有所協助。