Home > Article > Backend Development > About the logging function in the Yii framework of PHP
This article mainly introduces the logs in the Yii framework of PHP. The analysis of logs is the basis for daily website maintenance. Yii provides a relatively powerful log function. Friends who need it can refer to it
Yii page-level log enabled
Add the log section in Main.php,
Display the page log array below ('class'=>'CWebLogRoute', 'levels'=>'trace ', //The level is trace 'categories'=>'system.db.*' //Only display information about the database, including database connection, database execution statement),
is as follows:
'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), // 下面显示页面日志 array( 'class'=>'CWebLogRoute', 'levels'=>'trace', //级别为trace 'categories'=>'system.db.*' //只显示关于数据库信息,包括数据库连接,数据库执行语句 ), // uncomment the following to show log messages on web pages /* array( 'class'=>'CWebLogRoute', ), */ ), ),
Expand the log component that comes with Yii2
<?php /** * author : forecho <caizhenghai@gmail.com> * createTime : 2015/12/22 18:13 * description: */ namespace common\components; use Yii; use yii\helpers\FileHelper; class FileTarget extends \yii\log\FileTarget { /** * @var bool 是否启用日志前缀 (@app/runtime/logs/error/20151223_app.log) */ public $enableDatePrefix = false; /** * @var bool 启用日志等级目录 */ public $enableCategoryDir = false; private $_logFilePath = ''; public function init() { if ($this->logFile === null) { $this->logFile = Yii::$app->getRuntimePath() . '/logs/app.log'; } else { $this->logFile = Yii::getAlias($this->logFile); } $this->_logFilePath = dirname($this->logFile); // 启用日志前缀 if ($this->enableDatePrefix) { $filename = basename($this->logFile); $this->logFile = $this->_logFilePath . '/' . date('Ymd') . '_' . $filename; } if (!is_dir($this->_logFilePath)) { FileHelper::createDirectory($this->_logFilePath, $this->dirMode, true); } if ($this->maxLogFiles < 1) { $this->maxLogFiles = 1; } if ($this->maxFileSize < 1) { $this->maxFileSize = 1; } } }
Use it like this in the configuration file:
'components' => [ 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ /** * 错误级别日志:当某些需要立马解决的致命问题发生的时候,调用此方法记录相关信息。 * 使用方法:Yii::error() */ [ 'class' => 'common\components\FileTarget', // 日志等级 'levels' => ['error'], // 被收集记录的额外数据 'logVars' => ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION','_SERVER'], // 指定日志保存的文件名 'logFile' => '@app/runtime/logs/error/app.log', // 是否开启日志 (@app/runtime/logs/error/20151223_app.log) 'enableDatePrefix' => true, 'maxFileSize' => 1024 * 1, 'maxLogFiles' => 100, ], /** * 警告级别日志:当某些期望之外的事情发生的时候,使用该方法。 * 使用方法:Yii::warning() */ [ 'class' => 'common\components\FileTarget', // 日志等级 'levels' => ['warning'], // 被收集记录的额外数据 'logVars' => ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION','_SERVER'], // 指定日志保存的文件名 'logFile' => '@app/runtime/logs/warning/app.log', // 是否开启日志 (@app/runtime/logs/warning/20151223_app.log) 'enableDatePrefix' => true, 'maxFileSize' => 1024 * 1, 'maxLogFiles' => 100, ], /** * info 级别日志:在某些位置记录一些比较有用的信息的时候使用。 * 使用方法:Yii::info() */ [ 'class' => 'common\components\FileTarget', // 日志等级 'levels' => ['info'], // 被收集记录的额外数据 'logVars' => ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION','_SERVER'], // 指定日志保存的文件名 'logFile' => '@app/runtime/logs/info/app.log', // 是否开启日志 (@app/runtime/logs/info/20151223_app.log) 'enableDatePrefix' => true, 'maxFileSize' => 1024 * 1, 'maxLogFiles' => 100, ], /** * trace 级别日志:记录关于某段代码运行的相关消息。主要是用于开发环境。 * 使用方法:Yii::trace() */ [ 'class' => 'common\components\FileTarget', // 日志等级 'levels' => ['trace'], // 被收集记录的额外数据 'logVars' => ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION','_SERVER'], // 指定日志保存的文件名 'logFile' => '@app/runtime/logs/trace/app.log', // 是否开启日志 (@app/runtime/logs/trace/20151223_app.log) 'enableDatePrefix' => true, 'maxFileSize' => 1024 * 1, 'maxLogFiles' => 100, ], ], ], ],
##Yii log logic
Yii uses a hierarchical log processing mechanism, that is, log collection and log final processing (as shown , save to file, save to data) are separated. The collection of log information is completed by CLogger (log recorder), and the distribution and processing of log information is distributed to processing objects (such as CFileLogRoute and inheritance under the logging directory) under the scheduling of CLogRouter (called the log routing manager) (from the CLogRoute class, called log processor), after repeatedly reading its source code, I was impressed by Yii's design ideas. Such layered processing makes it easy to flexibly expand.
The log information is divided into levels, such as ordinary info, profile, trace, warning, error levels. You can set filtering conditions in the log routing. For example, setting the levels attribute of CFileRoute can only process log information of the specified level. .
If called in the program:
Yii::log($message,CLogger::LEVEL_ERROR,$category);The corresponding process may be as follows:
Question: When was the log written to the file?
After repeated tracking, I found that the processor CLogRouter::processLogs() is bound to the OnEndRequest event of the Application object in the init method of the CLogRouter class. At the same time, the event processor CLogRouter::collectLogs method is also bound to the onFlush event of Yii::$_logger, which is used to refresh the log and write it to the file in a timely manner when there are too many log messages in Yii::log(). The code is as follows:
/** * Initializes this application component. * This method is required by the IApplicationComponent interface. */ public function init(){ parent::init(); foreach($this->_routes as $name=>$route) { $route=Yii::createComponent($route); $route->init(); $this->_routes[$name]=$route; } Yii::getLogger()->attachEventHandler('onFlush',array($this,'collectLogs')); Yii::app()->attachEventHandler('onEndRequest',array($this,'processLogs'));}And defined in the CApplication::run() method:
if($this->hasEventHandler('onEndRequest')) { $this->onEndRequest(new CEvent($this)); }At this point we can understand that CLogger (Yii::$_logger) only collects logs (records them into the content structure), and then calls CLogRouter from the $app object at the end of the program. processLogs for log processing. Yii supports multiple routing of logs. For example, the same log can be written to a file, displayed on the page, or even sent via email at the same time, or even recorded to the database at the same time. This is determined by the log in the configuration file: Routes configuration is implemented by configuring multiple elements for log:routes to achieve multiple route distribution. The filtering and recording of log information are processed by the final log processor.
The tasks to be completed by the log processor mainly include the following points: Obtain all logs from CLogger and filter them (mainly levels and categories defined by log:routes:levels/categories)
$logs=$logger->getLogs($this->levels,$this->categories); //执行过滤,只得到期望信息The log filtering has been completed and the next step is to perform final processing on the log (such as writing to file, record to database, etc.)
CFileLogRoute::processLogs($logs);But there is a small bug in this function. It only determines whether the log directory is writable, and there is no judgment. Whether the log file itself is writable. CFileLogRoute implements a log rotation function (LogRoate) similar to Linux, and stipulates the size of the log file. It is very thoughtful and perfect! I also want to learn from it and absorb its ideas!
Configuration in protected/config/main.php:
'preload'=>array('log'), components => array( 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning,trace', ), ) ) )
定义log组件需要预先加载(实例化)。配置使用CLogRouter作为日志路由管理器,并设置了其日志路由处理器(routes属性)及其配置属性。而preload, log属性的定义,均要应用到CWebApplication对象上(请参阅CApplication::__construct中的configure调用, configure从CModule继承而来)。而在CWebApplication的构造函数中执行preloadComponents(),就创建了log对象(即CLogRouter的实例)。
创建并初始化一个组件时,实际上调用的是CModule::getComponent, 这个调用中使用YiiBase::createComponent创建组件对象,并再调用组件的init初始化之。
再阅读CLogRouter::init()过程,在这里有两个关键之处,一是创建日志路由处理器(即决定日志的最终处理方式:写入文件,邮件发送等等),二是给应用程序对象绑定onEndRequest事件处理CLogRouter::processLogs()。而在CApplication::run()确实有相关代码用于运行onEndRequest事件处理句柄:
if($this->hasEventHandler('onEndRequest')) { $this->onEndRequest(new CEvent($this)); }
也就是说,日志的最终处理(比如写入文件,系统日志,发送邮件)是发生在应用程序运行完毕之后的。Yii使用事件机制,巧妙地实现了事件与处理句柄的关联。
也就是说,当应用程序运行完毕,将执行CLogRouter::processLogs,对日志进行处理,。CLogRouter被称之为日志路由管理器。每个日志路由处理器从CLooger对象中取得相应的日志(使用过滤机制),作最终处理。
具体而言Yii的日志系统,分为以下几个层次:
日志发送者,即程序中调用Yii::log($msg, $level, $category),将日志发送给CLogger对象
CLogger对象负责将日志记录暂存于内存之中程序运行结束后,log组件(日志路由管理器CLogRoute)的processLogs方法被激活执行,由其逐个调用日志路由器,作日志的最后处理。
更为详细的大致过程如下:
CApplication::__construct()中调用preloadComponents, 这导致log组件(CLogRoute)被实例化,并被调用init方法初始化。
log组件(CLogRoute)的init方法中,其是初始化日志路由,并给CApplication对象onEndRequest事件绑定处理流程processLogs。给CLooger组件的onFlush事件绑定处理流程collectLogs。
应用程序的其它部分通过调用Yii::log()向CLogger组件发送日志信息,CLogger组件将日志信息暂存到内存中。
CApplication执行完毕(run方法中),会激活onEndRequest事件,绑定的事件处理器processLogs被执行,日志被写入文件之中。 Yii的日志路由机制,给日志系统扩展带来了无限的灵活。并且其多道路由处理机制,可将同一份日志信息进行多种方式处理。
这里举出一个案例:发生error级别的数据库错误时,及时给相关维护人员发送电子邮件,并同时将这些日志记录到文件之中。规划思路,发送邮件和手机短信是两个不同的功能,Yii已经带了日志邮件发送组件(logging/CEmailLogRoute.php),但这个组件中却使用了php自带的mail函数,使用mail函数需要配置php.ini中的smtp主机,并且使用非验证发送方式,这种方式在目前的实际情况下已经完全不可使用。代替地我们需要使用带验证功能的smtp发送方式。在protected/components/目录下定义日志处理器类myEmailLogRoute,并让其继承自CEmailLogRoute,最主要的目的是重写CEmailLogRoute::sendEmail()方法 ,其中,SMTP的处理细节请自行完善(本文的重点是放在如何处理日志上,而不是发送邮件上)。
接下来,我们就可以定义日志路由处理,编辑protected/config/main.php, 在log组件的routes组件添加新的路由配置:
'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning,trace', ), array( 'class' => 'myEmailLogRoute', 'levels' => 'error', #所有异常的错误级别均为error, 'categories' => 'exception.CDbException', #数据库产生错误时,均会产生CDbException异常。 'host' => 'mail.163.com', 'port' => 25, 'user' => 'jeff_yu', 'password' => 'you password', 'timeout' => 30, 'emails' => 'jeff_yu@gmail.com', #日志接收人。 'sentFrom' => 'jeff_yu@gmail.com', ),
经过以上处理,即可使之实现我们的目的,当然你可以根据自己的需要进一步扩展之。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of About the logging function in the Yii framework of PHP. For more information, please follow other related articles on the PHP Chinese website!