侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

框架(架构)  /  管理员 发布于 7年前   141

本文实例讲述了YII Framework框架日志用法。分享给大家供大家参考,具体如下:

日志的作用(此处省略1000字)

YII中的日志很好很强大,允许你把日志信息存放到数据库,发送到制定email,存放咋文件中,意见显示页面是,甚至可以用来做性能分析。

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',    ),    */  ),),

YII中日志的基本使用:

可以通过YII提供的Yii::log和Yii::trace进行日志信息的输出,两者的区别看看定义就知道了。

函数定义

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:你要输出的日志信息

$category:日志信息所属分类

$level:日志信息的级别:

const LEVEL_TRACE='trace';用于调试环境,追踪程序执行流程
const LEVEL_WARNING='warning';警告信息
const LEVEL_ERROR='error';致命错误信息
const LEVEL_INFO='info';普通提示信息
const LEVEL_PROFILE='profile';性能调试信息

基本使用方法举例

YII中日志的输出位置

上文提到YII中日志的输出位置可以定义为很多位置。主要通过配置文件修改例如:

'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',    ),  ),),

不仅输出到日志文件中,还输出到web页面上。

配置文件中:

routes用于配置日志输出的位置,
class是日志,日志路由的类名
levels是日志的顶级,字符串序列,用都好分割。具体对应CLooger中的常量

注意:

日志文件的存放位置是:/yii_dev/testwebap/protected/runtime/application.log

官方的日志介绍的很详细,但是后半部分中文翻译缺失了,这里进行翻译补全。

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'=>'[email protected]',        ),      ),    ),  ),)

在上面的例子中,我们定义了两个日志路由。第一个是 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.

框架可能在许多数情况下会用到日志过滤器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程序设计有所帮助。

您可能感兴趣的文章:

  • PHP的Yii框架的常用日志操作总结
  • 全面解读PHP的Yii框架中的日志功能
  • 详解PHP的Yii框架中日志的相关配置及使用
  • Yii2框架中日志的使用方法分析
  • Yii框架实现记录日志到自定义文件的方法
  • Yii框架日志记录Logging操作示例
  • Yii配置文件用法详解
  • YII2 实现多语言配置的方法分享
  • yii2 数据库读写分离配置示例
  • Yii框架日志操作图文与实例详解


  • 上一条:
    YII Framework框架教程之安全方案详解
    下一条:
    YII Framework教程之异常处理详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客