This article describes the usage of YII Framework log in examples. Share it with everyone for your reference, the details are as follows:
The role of logs (1000 words omitted here)
The log in YII is very good and powerful. It allows you to store the log information in the database, send it to a designated email, store it in a file, display the opinion page, and even use it for performance analysis.
Basic configuration of logs in YII:/yii_dev/testwebap/protected/config/main.php
'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), // uncomment the following to show log messages on web pages /* array( 'class'=>'CWebLogRoute', ), */ ), ),
Basic use of logs in YII :
You can output log information through Yii::log and Yii::trace provided by YII. The difference between the two can be understood by looking at the definition.
Function definition
public static function trace($msg,$category='application') { if(YII_DEBUG) self::log($msg,CLogger::LEVEL_TRACE,$category); } 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; } } } self::$_logger->log($msg,$level,$category); }
$msg: The log information you want to output
$category: The category to which the log information belongs
$level: Level of log information:
const LEVEL_TRACE='trace'; used in debugging environment to track program execution flow
const LEVEL_WARNING='warning'; warning message
const LEVEL_ERROR='error';Fatal error message
const LEVEL_INFO='info';General prompt information
const LEVEL_PROFILE='profile';Performance debugging information
Examples of basic usage
<?php class DefaultController extends Controller { public function actionCache () { $category='system.testmod.defaultController'; $level=CLogger::LEVEL_INFO; $msg='action begin '; Yii::log($msg,$level,$category); } }
The output location of the log in YII
As mentioned above, the output location of logs in YII can be defined in many locations. Mainly modified through configuration files, for example:
'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), // uncomment the following to show log messages on web pages array( 'class'=>'CWebLogRoute', ), ), ),
Not only output to the log file, but also output to the web page.
In configuration file:
routes is used to configure the location of log output,
class is log, the class name of log routing
Levels are the top level of the log, a sequence of strings, easy to split. Specifically corresponding to the constants in CLooger
Attention:
The storage location of the log file is:/yii_dev/testwebap/protected/runtime/application.log
The official log is very detailed, but the Chinese translation of the second half is missing. Here is the translation.
Yii provides a flexible and scalable logging function. Recorded logs can be classified by log level and information classification. By using level and category filters, selected information can be further routed to different destinations, such as a file, email, browser window, etc.
1. Information record
Information can be logged through Yii::log or Yii::trace. The difference is that the latter only logs information when the application is running in debug mode.
Yii::log($message, $level, $category); Yii::trace($message, $category);
When recording information, we need to specify its category and level. Category is a string with a format similar to path alias. For example, if a message is recorded in CController, we can use system.web.CController as the classification. The information level should be one of the following values:
trace: This is the level used in Yii::trace. It is used to track the execution flow of a program during development.
info: This is used to record common information.
profile: This is a performance overview (profile). More detailed instructions will follow shortly.
warning: This is used for warning information.
error: This is used for fatal error messages.
2. Information routing
The information recorded through Yii::log or Yii::trace is saved in memory. We usually need to display them in a browser window, or save them to some persistent storage such as a file or email. This is called message routing, i.e. sending messages to different destinations.
In Yii, information routing is managed by an application component called CLogRouter. It is responsible for managing a series of things called log routing. Each log route represents a separate log destination. Messages sent through a log route are filtered by their level and category.
To use message routing, we need to install and preload a CLogRouter application component. We also need to configure its routes attribute for the log routes we want. The code below demonstrates an example of the required application configuration:
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', ), ), ), ), )
In the above example, we defined two log routes. The first is CFileLogRoute, which saves the information in a file located in the application's runtime directory. And only information with level trace or info and categories beginning with system. will be saved. The second route is CEmailLogRoute, which will send information to the specified email address, and only messages with level error or warning will be sent.
In Yii, the following log routes are available:
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.
框架可能在许多数情况下会用到日志过滤器CLogFilter来过滤日志。默认情况下,CLogFilter日志消息包含了许多系统上下文信息的变量,像$ _GET,$_SERVER。 CLogFilter也可以配置的前缀与会话ID,用户名等,我们在检查无数记录的消息每个记录的消息时,这可能会极大地简化了搜索难度
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 includingyii.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.
从版本1.0.7开始,Yii的日志记录可以采用堆栈的方式记录消息,此功能默认是关闭的,因为它会降低性能。要使用此功能,只需在入口脚本(前includingyii.php)定义一个命名为YII_TRACE_LEVEL的常量即一个大于0的整数。 Yii将在堆栈信息中追加应用程序要到的每一个文件名和行号。可以通过设置YII_TRACE_LEVEL来设定堆栈的层数。这种方式在开发阶段特别有用,因为它可以帮助我们确定触发跟踪消息的地方。
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.
其中blockID是一个标识代码块的唯一ID。
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.
为了显示分析结果,我们需要为CLogRouter增加CProfileLogRoute路由。然后通过CProfileLogRoute可以把性能测试结果显示在当前页面结束。
6. Profiling SQL Executions 分析SQL执行
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 endProfilestatements 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.
在数据库开发中分析是特别有用的,因为SQL执行往往是应用程序的主要性能瓶颈。尽管我们可以手动在每个SQL执行的适当的地方插入beginProfile和endProfile来衡量花费的时间,但从1.0.6版本开始,Yii提供了更系统的方法来解决这个问题。
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 aforementionedCProfileLogRoute, 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.
再实际的应用程序当中通过设置CDbConnection::enableProfiling爱分析每一个正在执行的SQL语句。使用 CProfileLogRoute,结果可以很容易地显示。它可以显示我们是在执行什么SQL语句花费多少时间。我们也可以调用CDbConnection:getStats()来分析检索SQL语句的执行总数和其总的执行时间。
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。