`

Yii分析3:Yii日志记录

Web 
阅读更多

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日志记录类关系

  • 大小: 23.6 KB
1
3
分享到:
评论

相关推荐

    Yii框架日志记录Logging操作示例

    本文实例讲述了Yii框架日志记录Logging操作。分享给大家供大家参考,具体如下: 1、Yii::getLogger()->log($message, $level, $category = 'application') 2、Yii::trace($message, $category = 'application'); 3...

    yii2-consolelog:yii2的控制台日志

    控制台记录器 将输出转储到控制台,以进行控制台应用程序调试 安装 添加 "pahanini/yii2-consolelog": "*" 到composer.json文件的require部分。 用法 return [ 'id' => 'app-console' , 'bootstrap' => [ 'log' ...

    Yii框架实现记录日志到自定义文件的方法

    默认情况下,Yii::log($msg, $level, $category)会把日志记录到runtime/application.log文件中 日志格式如下: [时间] – [级别] – [类别] – [内容] 2013/05/03 17:33:08 [error] [application] test 但有时候...

    YII2框架中日志的配置与使用方法实例分析

    本文实例讲述了YII2框架中日志的配置与使用方法。分享给大家供大家参考,具体如下: YII2中给我们提供了非常方便的日志组件,只需要简单配置... //YII_DEBUG开启时,日志消息被记录时,追加最多3个调用堆栈信息 '

    yii2_rest:具有高级日志记录和消息加密功能的 Yii2 REST API 模板

    yii2_rest 具有高级日志记录和消息加密功能的 Yii2 REST API 模板

    PHP的Yii框架的常用日志操作总结

    调用日志记录的方法 在主应用的配置文件(例如basic下面的web.php)中配置好日志的过滤和导出的设置 检查不同场景下经过过滤之后的日志信息 记录日志 记录日志其实就是简简单单的调用如下的方法: [[Yii::trace()...

    Yii2框架中日志的使用方法分析

    本文实例讲述了Yii2框架中日志的使用方法。...在Yii2中,面向对象的设计贯彻得更加彻底,日志记录功能被转移到Logger类中,并支持多种输出目标(Targets)。 Yii2中的日志使用方法 为了记录日志,你首先需要获取

    yiiframework官方最新版,包括源程序、api、文档

     11、错误处理和日志记录:错误的处理很好的呈现出来,日志信息可以分类,过滤并分配到不同的位置。  12、安全:Yii配备了许多安全的措施,以帮助安全的Web应用程序,以防止网络攻击。这些措施包括跨站点脚本(XSS...

    yii2-psr3-log-adapter:允许您将Yii2记录器与需要PSR3兼容记录器的库一起使用

    请注意,Yii2的日志记录级别数量有限,因此此类将尝试对提供的PSR3级别使用最接近的Yii2等效项。安装由于此程序包尚在开发中,因此您需要按如下方式手动将此存储库添加到composer.json中: " repositories " : [ { ...

    yii-fluentd-logroute:用于 Yii1 的 Fluentd 的日志路由器

    Fluentd for Yii 1.1.* 的日志路由如何使用> 在应用程序内正常日志记录(yii 可以通过在消息中附加字符串来添加跟踪信息) Yii :: log ( 'test-message' , CLogger :: LEVEL_INFO , 'fluent-log' );//{"level":"info...

    yii2-js-log:将 javascript 错误记录到 Yii 日志中

    Yii2 JavaScript 记录器 用于 yii2 应用程序的简单 javascript 记录器 安装 安装此扩展的首选方法是通过 。 要么跑 php composer.phar require --prefer-dist trntv/yii2-js-log "*" 或添加 "trntv/yii2-js-log":...

    Yii框架日志操作图文与实例详解

    将日志记录到文本中. Yii::log(test); //写入测试日志 //找到配置文件 component->log 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'warning,...

    yii2-mongolog:用于 MongoDB 中 Web 应用程序用户活动日志的 Yii2 模块

    yii2-mongolog是一个 Yii2 模块,用于在 MongoDB 中存储 Web 应用程序用户的活动日志。 安装 安装此扩展的首选方法是通过 。 配置 将mongolog模块添加到配置的模块部分。 为存储日志数据设置 MongoDB 集合名称。 ...

    Yii2中文手册(中文教程完整版)

    编撰中 活动记录(Active Record) - 活动记录对象关系映射(ORM),检索和操作记录、定义关联关系 编撰中 数据库迁移(Migration) - 在团体开发中对你的数据库使用版本控制 待定中 Sphinx 待定中 Redis 待定中 ...

    yii2-shop:基于Yii2制作的电子商城

    加入 Kafka异步记录日志(自行开启) 后台RBAC权限控制 接入 支付宝 接入 七牛云,ueditor(图片自动上传七牛云) 接入 QQ互联,可以使用QQ登陆 qq和支付宝都是开发者模式,只能允许开发者使用,请自行修改成自己的再进行...

    yii2-admin:Yii2基础的后台管理

    增加后台管理员操作日志记录 测试了js和css合并压缩,只是把后台各页面通用的合并了一下,生产环境下,如果第一次或者是修改了合并中引用的js或css,需要运行命令yii asset backend/assets....

    yii2-psr-log-target:Yii 2.0日志目标,能够将消息写到与PSR-3兼容的记录器

    允许您使用任何与PSR-3兼容的记录器(例如处理日志。 安装 composer require "samdark/yii2-psr-log-target" 用法 为了使用PsrTarget您应该像下面这样配置log应用程序组件: // $psrLogger should be an instance ...

    yii2-mougrim-logger

    该扩展提供了所有期望分析的日志。好处具有下一个优点: 灵活的配置; 类似于Apache log4php的界面(具有调试日志级别); 高于yii2记录器性能。 有关更多信息和基准测试结果,请参见。安装安装此扩展的首选方法是...

Global site tag (gtag.js) - Google Analytics