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);
- Generate CLogger instance
- If YII_DEBUG and YII_TRACE_LEVEL have been defined as valid values, and the log level is not profile, call traceback information will be generated and appended to the log information.
- Call CLogger::log($msg,$level,$category) to collect logs. In fact, the logs are not written to the file at this time, but are only temporarily stored in the memory.
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'));}
if($this->hasEventHandler('onEndRequest')) { $this->onEndRequest(new CEvent($this)); }
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); //执行过滤,只得到期望信息
CFileLogRoute::processLogs($logs);
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
