YII框架分析筆記10:日誌

yii框架中日誌組件記錄的等級5類,在CLogger已通過常量定義:
const LEVEL_TRACE='trace';
const LEVEL_WARNING='warning';
const LEVEL_ERROR='error';
const LEVEL_INFO='info';
const LEVEL_PROFILE='profile';
CLogger爲所有日誌寫入和獲取提供接口,通過日誌路由管理類CLogRouter將日誌分發到不同日誌展現或存儲介質中。


日誌組件配置

'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
array(
'class'=>'CWebLogRoute',
'levels'=>'info',
'showInFireBug' => true
),             
),
),

日誌路由初始化

在log組件被創建的時候,會通過CLogRouter::init()初始化配置中各個日誌路由,並添加刷新和請求結束事件,這個兩個事件對YII日誌性能提升有很大幫助。YII默認在一次請求中日誌的數量小於1000的情況下,日誌數據都放在內存中,當大於1000的時候執行onflush事件,將日誌刷新到接收介質上,當請求結束的時候執行onEndRequest再刷新一次日誌,這樣做減少了大量IO操作。

/**
 * Initializes this application component.
 * This method is required by the IApplicationComponent interface.
 */
public function init()
{
	parent::init();
	foreach($this->_routes as $name=>$route)
	{
		$route=Yii::createComponent($route);
		$route->init();
		$this->_routes[$name]=$route;
	}
	Yii::getLogger()->attachEventHandler('onFlush',array($this,'collectLogs'));
	Yii::app()->attachEventHandler('onEndRequest',array($this,'processLogs'));
}

日誌調用

對日誌的操作是通過YII::log()靜態方法實現對CLogger的調用,下面是CLogger的log方法,日誌會保存在$this->_logs[]中,當觸發刷新事件時,執行刷新處理過程。

/**
 * Logs a message.
 * Messages logged by this method may be retrieved back via {@link getLogs}.
 * @param string $message message to be logged
 * @param string $level level of the message (e.g. 'Trace', 'Warning', 'Error'). It is case-insensitive.
 * @param string $category category of the message (e.g. 'system.web'). It is case-insensitive.
 * @see getLogs
 */
public function log($message,$level='info',$category='application')
{
	
	$this->_logs[]=array($message,$level,$category,microtime(true));
	$this->_logCount++;
	if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
	{
		$this->_processing=true;
		$this->flush($this->autoDump);
		$this->_processing=false;
	}
}
以觸發onflush事件爲例,日誌路由CLogRouter::collectLogs($event)將日誌對象傳給各個日誌的collectLogs()中,然後通過processLogs()來處理不同的日誌等級對應的展現方式。
/**
 * Retrieves filtered log messages from logger for further processing.
 * @param CLogger $logger logger instance
 * @param boolean $processLogs whether to process the logs after they are collected from the logger
 */
public function collectLogs($logger, $processLogs=false)
{
	$logs=$logger->getLogs($this->levels,$this->categories);
	$this->logs=empty($this->logs) ? $logs : array_merge($this->logs,$logs);
	if($processLogs && !empty($this->logs))
	{
		if($this->filter!==null)
			Yii::createComponent($this->filter)->filter($this->logs);
		$this->processLogs($this->logs);
		$this->logs=array();
	}
}

實例

Yii::log("test",CLogger::LEVEL_INFO);
Yii::log("test2",CLogger::LEVEL_INFO);

下面分別是CWebLogRoute在web中和chrome控制檯中顯示日誌的效果。(默認時間和北京時間相差8小時)




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章