博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Yii分析3:Yii日志记录
阅读量:4078 次
发布时间:2019-05-25

本文共 6437 字,大约阅读时间需要 21 分钟。

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);

 

至此,整个记录日志的过程就清楚了,下图是类关系:

 

Yii日志记录类关系

转载地址:http://nasni.baihongyu.com/

你可能感兴趣的文章
【JAVA数据结构】先进先出队列
查看>>
String类的intern方法随笔
查看>>
【泛型】一个简易的对象间转换的工具类(DO转VO)
查看>>
1.随机函数,计算机运行的基石
查看>>
MouseEvent的e.stageX是Number型,可见as3作者的考虑
查看>>
在mc中直接加aswing组件,该组件还需最后用validate()方法
查看>>
移植Vim配色方案到Eclipse
查看>>
从超链接调用ActionScript
查看>>
谈谈加密和混淆吧[转]
查看>>
TCP的几个状态对于我们分析所起的作用SYN, FIN, ACK, PSH,
查看>>
网络游戏客户端的日志输出
查看>>
关于按钮的mouseOver和rollOver
查看>>
《多线程服务器的适用场合》例释与答疑
查看>>
Netty框架
查看>>
Socket经验记录
查看>>
对RTMP视频流进行BitmapData.draw()出错的解决办法
查看>>
FMS 客户端带宽计算、带宽限制
查看>>
在线视频聊天(客服)系统开发那点事儿
查看>>
SecurityError Error 2148 SWF 不能访问本地资源
查看>>
Flex4的可视化显示对象
查看>>