加载中...

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小时)





还没有评论.