时间:2022-04-19 编辑:
Yii的自带组件有一个很实用的日志记录组件,使用方法可以参考Yii官方文档:http://www.yiiframework.com/doc/guide/1.1/zh_cn/topics.logging,在文档中提到,只要我们在应用程序配置文件中配置了log组件,那么就可以使用
Yii::log($msg, $level, $category);
进行日志记录了。
配置项示例如下:
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',),),),),)
log组件的核心是CLogRouter,如果想使用多种方式记录日志,就必须配置routes,可用的route有:
• CDbLogRoute: 将信息保存到数据库的表中。
• CEmailLogRoute: 发送信息到指定的 Email 地址。
• CFileLogRoute: 保存信息到应用程序 runtime 目录中的一个文件中。
• CWebLogRoute: 将 信息 显示在当前页面的底部。
• CProfileLogRoute: 在页面的底部显示概述(profiling)信息。
下面分析一下log的实现:
首先看一下CLogRouter的代码:
/** * Initializes this application component. * This method is required by the IApplicationComponent interface. */public function init(){parent::init();foreach($this->_routes as $name=>$route){//初始化从配置文件读取的route,保存在成员变量里$route=Yii::createComponent($route);$route->init();$this->_routes[$name]=$route;}//绑定事件,如果触发了一个onFlush事件,则调用CLogRouter的collectLogs方法Yii::getLogger()->attachEventHandler('onFlush',array($this,'collectLogs'));//绑定事件,如果触发了一个onEndRequest事件,则调用ClogRouter的processLogs方法Yii::app()->attachEventHandler('onEndRequest',array($this,'processLogs'));}/** * Collects log messages from a logger. * This method is an event handler to the {@link CLogger::onFlush} event. * @param CEvent $event event parameter */public function collectLogs($event){$logger=Yii::getLogger();//调用每个route的collectLogs方法foreach($this->_routes as $route){if($route->enabled)$route->collectLogs($logger,false);}}
接着,我们看一下在调用Yii::log();时,发生了什么:
/** * Logs a message. * Messages logged by this method may be retrieved via {@link CLogger::getLogs} * and may be recorded in different media, such as file, email, database, using * {@link CLogRouter}. * @param string $msg 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. */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;}}}//调用CLogger的log方法self::$_logger->log($msg,$level,$category);}
继续看CLogger:
class CLogger extends CComponent{const LEVEL_TRACE='trace';const LEVEL_WARNING='warning';const LEVEL_ERROR='error';const LEVEL_INFO='info';const LEVEL_PROFILE='profile';/** * @var integer how many messages should be logged before they are flushed to destinations. * Defaults to 10,000, meaning for every 10,000 messages, the {@link flush} method will be * automatically invoked once. If this is 0, it means messages will never be flushed automatically. * @since 1.1.0 */public $autoFlush=10000;……/** * 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++;//如果数组数量到了autoFlush定义的数量,那么调用flush方法if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush)$this->flush();}/** * Removes all recorded messages from the memory. * This method will raise an {@link onFlush} event. * The attached event handlers can process the log messages before they are removed. * @since 1.1.0 */public function flush(){//触发onflush方法,这时会触发CLogRouter的onflush事件//参见上面CLogRouter的代码,会调用collectLogs方法$this->onFlush(new CEvent($this));//清空日志数据$this->_logs=array();$this->_logCount=0;}
回到CLogRouter,调用collectLogs实际是调用配置中的每一个Route的collectlogs方法
,这个方法是所有route继承自CLogRoute(注意,不是CLogRouter)的:
/** * 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);//调用processlog方法$this->processLogs($this->logs);}}/** * Processes log messages and sends them to specific destination. * Derived child classes must implement this method. * @param array $logs list of messages. Each array elements represents one message * with the following structure: * array( * [0] => message (string) * [1] => level (string) * [2] => category (string) * [3] => timestamp (float, obtained by microtime(true)); *///processlog是由CLogRoute的各个route子类实现的//例如数据库route用数据库存储,文件route用文件存储……abstract protected function processLogs($logs);
至此,整个记录日志的过程就清楚了,下图是类关系: