`
zccst
  • 浏览: 3310514 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

yii之Log(日志)使用

    博客分类:
  • YII
 
阅读更多
作者:zccst


Yii 提供了一个灵活可扩展的日志功能。记录的日志可以通过日志级别和信息分类进行归类。通过使用级别和分类过滤器,所选的信息还可以进一步路由到不同的目的地,例如一个文件,Email,浏览器窗口等。

1. 信息记录

信息可以通过 Yii::log 或 Yii::trace 记录。其区别是后者只在当应用程序运行在 调试模式(debug mode) 中时才会记录信息。
Yii::log($message, $level, $category);
Yii::trace($message, $category);

当记录信息时,我们需要指定它的分类和级别分类是一段格式类似于 路径别名 的字符串。例如,如果一条信息是在 CController 中记录的,我们可以使用 system.web.CController 作为分类。信息级别应该是下列值中的一种:

    trace: 这是在 Yii::trace 中使用的级别。它用于在开发中跟踪程序的执行流程。

    info: 这个用于记录普通的信息。

    profile: 这个是性能概述(profile)。下面马上会有更详细的说明。

    warning: 这个用于警告(warning)信息。

    error: 这个用于致命错误(fatal error)信息。


2. 信息路由

通过 Yii::log 或 Yii::trace 记录的信息是保存在内存中的。我们通常需要将它们显示到浏览器窗口中,或者将他们保存到一些持久存储例如文件、Email中。这个就叫作 信息路由,例如,发送信息到不同的目的地。

在 Yii 中,信息路由是由一个叫做 CLogRouter 的应用组件管理的。它负责管理一系列称作 日志路由 的东西。每个日志路由代表一个单独的日志目的地。通过一个日志路由发送的信息会被他们的级别和分类过滤。

要使用信息路由,我们需要安装并预加载一个 CLogRouter 应用组件。我们也还需要配置它的 routes 属性为我们想要的那些日志路由。下面的代码演示了一个所需的 应用配置 示例:
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',
                ),
            ),
        ),
    ),
)

在上面的例子中,我们定义了两个日志路由。第一个是 CFileLogRoute ,它会把信息保存在位于应用程序 runtime 目录中的一个文件中。而且只有级别为 trace 或 info 、分类以 system. 开头的信息才会被保存。 第二个路由是 CEmailLogRoute ,它会将信息发送到指定的 email 地址,且只有级别为 error 或 warning 的才会发送。

在 Yii 中,有下列几种日志路由可用:

CDbLogRoute: 将信息保存到数据库的表中。
CEmailLogRoute: 发送信息到指定的 Email 地址。
CFileLogRoute: 保存信息到应用程序 runtime 目录中的一个文件中。
CWebLogRoute: 将 信息 显示在当前页面的底部。
CProfileLogRoute: 在页面的底部显示概述(profiling)信息。

注:信息路由发生在当前请求周期最后的 onEndRequest 事件触发时。 要显式终止当前请求过程,请调用 CApplication::end() 而不是使用 die() 或 exit(),因为 CApplication::end() 将会触发 onEndRequest 事件, 这样信息才会被顺利地记录。


3. 信息过滤

正如我们所提到的,信息可以在他们被发送到一个日志路由之前通过它们的级别和分类过滤。这是通过设置对应日志路由的 levels 和 categories 属性完成的。多个级别或分类应使用逗号连接。

由于信息分类是类似 xxx.yyy.zzz 格式的,我们可以将其视为一个分类层级。具体地,我们说 xxx 是 xxx.yyy 的父级,而xxx.yyy 又是 xxx.yyy.zzz 的父级。这样我们就可以使用 xxx.* 表示分类 xxx 及其所有的子级和孙级分类




4. 记录上下文信息

从版本 1.0.6 起,我们可以设置记录附加的上下文信息,比如 PHP 的预定义变量(例如 $_GET, $_SERVER),session ID,用户名等。这是通过指定一个日志路由的 CLogRoute::filter属性为一个合适的日志过滤规则实现的。

The framework comes with the convenient CLogFilter that may be used as the needed log filter in most cases. By default, CLogFilter will log a message with variables like $_GET, $_SERVER which often contains valuable system context information. CLogFilter can also be configured to prefix each logged message with session ID, username, etc., which may greatly simplifying the global search when we are checking the numerous logged messages.

The following configuration shows how to enable logging context information. Note that each log route may have its own log filter. And by default, a log route does not have a log filter.
array(
    ......
    'preload'=>array('log'),
    'components'=>array(
        ......
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error',
                    'filter'=>'CLogFilter',
                ),
                ...other log routes...
            ),
        ),
    ),
)

Starting from version 1.0.7, Yii supports logging call stack information in the messages that are logged by calling Yii::trace. This feature is disabled by default because it lowers performance. To use this feature, simply define a constant named YII_TRACE_LEVEL at the beginning of the entry script (before including yii.php) to be an integer greater than 0. Yii will then append to every trace message with the file name and line number of the call stacks belonging to application code. The number YII_TRACE_LEVEL determines how many layers of each call stack should be recorded. This information is particularly useful during development stage as it can help us identify the places that trigger the trace messages.


5. Performance Profiling

Performance profiling is a special type of message logging. Performance profiling can be used to measure the time needed for the specified code blocks and find out what the performance bottleneck is.

To use performance profiling, we need to identify which code blocks need to be profiled. We mark the beginning and the end of each code block by inserting the following methods:

Yii::beginProfile('blockID');
...code block being profiled...
Yii::endProfile('blockID');

where blockID is an ID that uniquely identifies the code block.

Note, code blocks need to be nested properly. That is, a code block cannot intersect with another. It must be either at a parallel level or be completely enclosed by the other code block.

To show profiling result, we need to install a CLogRouter application component with a CProfileLogRoute log route. This is the same as we do with normal message routing. The CProfileLogRoute route will display the performance results at the end of the current page.


6. Profiling SQL Executions

Profiling is especially useful when working with database since SQL executions are often the main performance bottleneck of an application. While we can manually insert beginProfile and endProfile statements at appropriate places to measure the time spent in each SQL execution, starting from version 1.0.6, Yii provides a more systematic approach to solve this problem.

By setting CDbConnection::enableProfiling to be true in the application configuration, every SQL statement being executed will be profiled. The results can be readily displayed using the aforementioned CProfileLogRoute, which can show us how much time is spent in executing what SQL statement. We can also call CDbConnection::getStats() to retrieve the total number SQL statements executed and their total execution time.



使用实例:想查看如下结果,但由于较大,var_dump时浏览器会崩溃,于是想到如果知道执行的sql是什么,那么就可以推出执行后的结果是什么。

//1,在 ../config/main.php里增加'class'=>'CProfileLogRoute'
'log'=>array(
			'class'=>'CLogRouter',
			'routes'=>array(
				array(
					'class'=>'CFileLogRoute',
					'levels'=>'error, warning',
				),
				/*  此处为本次增加 */
				array(
					'class'=>'CProfileLogRoute',
				),
				// uncomment the following to show log messages on web pages
				/*
				array(
					'class'=>'CWebLogRoute',
				),
				*/
			),
		),

//2,在源码处增加三行代码
$c = new CDbCriteria();
$c->join = "JOIN idc_user on t.id=idc_user.user_id";
$c->condition = "idc_user.idc_id=$idc_id";

Yii::beginProfile('block1');
$r = User::model()->with('Idcs')->findAll($c);
Yii::endProfile('block1');


//整理打印结果如下
SELECT `t`.`id` AS `t0_c0` , `t`.`username` AS `t0_c1` , `t`.`password` AS `t0_c2` , `t`.`display_name` AS `t0_c3` , `t`.`tel` AS `t0_c4` , `t`.`mobile` AS `t0_c5` , `t`.`email` AS `t0_c6` , `t`.`hi_id` AS `t0_c7` , `t`.`company_id` AS `t0_c8` , `t`.`last_login_at` AS `t0_c9` , `t`.`last_pwd_updated_at` AS `t0_c10` , `t`.`created_at` AS `t0_c11` , `Idcs`.`id` AS `t1_c0` , `Idcs`.`name` AS `t1_c1` , `Idcs`.`desc` AS `t1_c2` , `Idcs`.`created_at` AS `t1_c3` , `Idcs`.`chinese_name` AS `t1_c4` , `Idcs`.`clientele` AS `t1_c5` , `Idcs`.`contact_man` AS `t1_c6` , `Idcs`.`contact_phone` AS `t1_c7` , `Idcs`.`post_code` AS `t1_c8` , `Idcs`.`address` AS `t1_c9` , `Idcs`.`email` AS `t1_c10` , `Idcs`.`weight` AS `t1_c11` , `Idcs`.`pool_id` AS `t1_c12` , `Idcs`.`provider_id` AS `t1_c13`
FROM `user` `t`
JOIN idc_user ON t.id = idc_user.user_id
LEFT OUTER JOIN `idc_user` `Idcs_Idcs` ON ( `t`.`id` = `Idcs_Idcs`.`user_id` )
LEFT OUTER JOIN `idc` `Idcs` ON ( `Idcs`.`id` = `Idcs_Idcs`.`idc_id` )
WHERE (
idc_user.idc_id =6
)

//打印结果如下
block2 	1 	0.01122 	0.01122 	0.01122 	0.01122
system.db.CDbCommand.query(SELECT `t`.`id` AS `t0_c0`, `t`.`username` AS `t0_c1`, `t`.`password` AS `t0_c2`, `t`.`display_name` AS `t0_c3`, `t`.`tel` AS `t0_c4`, `t`.`mobile` AS `t0_c5`, `t`.`email` AS `t0_c6`, `t`.`hi_id` AS `t0_c7`, `t`.`company_id` AS `t0_c8`, `t`.`last_login_at` AS `t0_c9`, `t`.`last_pwd_updated_at` AS `t0_c10`, `t`.`created_at` AS `t0_c11`, `Idcs`.`id` AS `t1_c0`, `Idcs`.`name` AS `t1_c1`, `Idcs`.`desc` AS `t1_c2`, `Idcs`.`created_at` AS `t1_c3`, `Idcs`.`chinese_name` AS `t1_c4`, `Idcs`.`clientele` AS `t1_c5`, `Idcs`.`contact_man` AS `t1_c6`, `Idcs`.`contact_phone` AS `t1_c7`, `Idcs`.`post_code` AS `t1_c8`, `Idcs`.`address` AS `t1_c9`, `Idcs`.`email` AS `t1_c10`, `Idcs`.`weight` AS `t1_c11`, `Idcs`.`pool_id` AS `t1_c12`, `Idcs`.`provider_id` AS `t1_c13` FROM `user` `t` JOIN idc_user on t.id=idc_user.user_id LEFT OUTER JOIN `idc_user` `Idcs_Idcs` ON (`t`.`id`=`Idcs_Idcs`.`user_id`) LEFT OUTER JOIN `idc` `Idcs` ON (`Idcs`.`id`=`Idcs_Idcs`.`idc_id`) WHERE (idc_user.idc_id=6)) 	1 	0.00086 	0.00086 	0.00086 	0.00086
system.db.CDbCommand.query(SHOW COLUMNS FROM `user`) 	1 	0.00083 	0.00083 	0.00083 	0.00083
system.db.CDbCommand.query(SHOW COLUMNS FROM `idc`) 	1 	0.00078 	0.00078 	0.00078 	0.00078
system.db.CDbCommand.query(SHOW COLUMNS FROM `idc_user`) 	1 	0.00060 	0.00060 	0.00060 	0.00060
system.db.CDbCommand.query( SELECT data FROM YiiSession WHERE expire>1339135578 AND id=:id ) 	1 	0.00047 	0.00047 	0.00047 	0.00047
system.db.CDbCommand.query(SELECT * FROM `user` `t` WHERE `t`.`id`=8 LIMIT 1) 	1 	0.00045 	0.00045 	0.00045 	0.00045
system.db.CDbCommand.query(SHOW CREATE TABLE `user`) 	1 	0.00038 	0.00038 	0.00038 	0.00038
system.db.CDbCommand.query(SHOW CREATE TABLE `idc`) 	1 	0.00038 	0.00038 	0.00038 	0.00038
system.db.CDbCommand.query(SHOW CREATE TABLE `idc_user`) 	1 	0.00036 	0.00036 	0.00036 	0.00036






如果您觉得本文的内容对您的学习有所帮助,您可以微信:
分享到:
评论

相关推荐

    yii2使用SeasLog写日志

    本篇文章将详细介绍如何在Yii2框架中使用SeasLog扩展来替换原生的日志模块,以提高写日志的效率。 首先,让我们了解SeasLog。SeasLog是一款高性能、易用的日志库,适用于PHP环境。它支持多级别日志、自定义日志格式...

    YII Framework框架教程之日志用法详解

    使用`Yii::log`或`Yii::trace`记录日志时,你可以指定消息内容、消息级别和消息类别。消息级别是区分不同类型日志消息的标识,如`LEVEL_TRACE`用于记录调试信息,`LEVEL_WARNING`记录警告信息等。而消息类别则用于...

    yii2-log:不同的 Yii2 日志传输

    yii2-log 不同的 Yii2 日志传输现已上市弹性搜索目标日志存储文件目标日志存储目标Redis目标安装安装此扩展的首选方法是通过 。 php composer.phar require --prefer-dist index0h/yii2-log " 0.0.3 " 或添加行到...

    yii2-log:Yii 2.0 框架日志类

    Yii 2.0 框架日志类 SyslogTarget 将日志写入 syslog。 安装 安装此扩展的首选方法是通过 。 跑步 php composer.phar require --prefer-dist dmstr/yii2-log "*" 用法 安装扩展后,只需通过以下方式在代码中使用它...

    yii2-consolelog:yii2的控制台日志

    "pahanini/yii2-consolelog": "*" 到composer.json文件的require部分。 用法 return [ 'id' => 'app-console' , 'bootstrap' => [ 'log' ], 'components' => [ 'log' => [ 'targets' => [ [ '...

    整合日志,权限,方便高效开发的yii项目

    1. **日志管理**:在Yii2中,日志是通过`Yii::$app->log`组件进行管理的。开发者可能已经设置好了不同的日志目标,如文件、数据库、邮件等,以便记录不同级别的信息(如错误、警告、调试等),这对于调试和问题追踪...

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

    Yii框架提供了强大的日志记录功能,下面将详细介绍Yii框架日志记录Logging的操作示例以及相关配置和使用技巧。 首先,Yii框架的日志记录可以通过多种方式实现,官方文档中提供了丰富的API调用方法。例如: 1. Yii:...

    yii2-telegram-log:Yii 2的电报日志目标

    Yii 2的电报日志目标 Yii 2的日志目标。 安装 安装此扩展的首选方法是通过 。 无论运行 composer require " sergeymakinen/yii2-telegram-log:^2.0 " 或添加 " sergeymakinen/yii2-telegram-log " : " ^2.0 " 到...

    Yii2实现log输出到file及database的方法

    `yii\log\FileTarget`类用于将日志记录到文件。具体配置如下: ```php 'components' => [ 'log' => [ 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'exportInterval' => 1, ], ], ], ] ``` 其中,`...

    详解PHP的Yii框架中日志的相关配置及使用

    在Yii框架中,日志使用主要通过`Yii::log()`和`Yii::trace()`两个函数实现。 `Yii::log()`函数用于记录一条日志消息,其基本用法如下: ```php Yii::log($message, $level, $category); ``` 其中,`$message`是...

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

    总之,Yii2框架中的日志使用方法比Yii1.x更加灵活且功能强大,它允许开发者通过简单的配置实现复杂的日志管理需求。此外,通过自定义日志输出目标,我们可以根据实际需求选择合适的日志记录方式,使得问题追踪和系统...

    yii-streamlog:将 Yii 1 日志发送到 stdoutstderr - 创建用于与 http 上提供的 php-fpmnginx Docker 堆栈一起使用

    将 Yii 1 日志发送到 stdout/stderr - 创建用于与提供的 php-fpm/nginx Docker 堆栈一起使用 感谢 Haensel 为! 安装 通过作曲家安装: composer require neam/yii-streamlog:* 或者下载扩展,将src文件夹复制到您...

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

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

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

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

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

    这是早期的原型。 当然,您可以使用它,但是... :-) 更好地完成它! Yii2 JavaScript 记录器 用于 yii2 应用程序的简单 javascript 记录器 ...= \trntv\yii\jslog\ AutoloadExample :: widget (); ?> ```

    yii2 通用后台系统

    Yii2 的 `yii\log` 组件可以帮助记录和分析系统运行中的事件和异常,而 `yii\swiftmailer` 可以方便地发送邮件通知。API接口开发则可以利用Yii2的RESTful特性,快速构建符合REST原则的API,方便前后端分离的项目开发...

Global site tag (gtag.js) - Google Analytics