search
HomeBackend DevelopmentPHP TutorialAbout 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 = &#39;&#39;;

  public function init()
  {
    if ($this->logFile === null) {
      $this->logFile = Yii::$app->getRuntimePath() . &#39;/logs/app.log&#39;;
    } else {
      $this->logFile = Yii::getAlias($this->logFile);
    }
    $this->_logFilePath = dirname($this->logFile);

    // 启用日志前缀
    if ($this->enableDatePrefix) {
      $filename = basename($this->logFile);
      $this->logFile = $this->_logFilePath . &#39;/&#39; . date(&#39;Ymd&#39;) . &#39;_&#39; . $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:

&#39;components&#39; => [
  &#39;log&#39; => [
    &#39;traceLevel&#39; => YII_DEBUG ? 3 : 0,
    &#39;targets&#39; => [
      /**
       * 错误级别日志:当某些需要立马解决的致命问题发生的时候,调用此方法记录相关信息。
       * 使用方法:Yii::error()
       */
      [
        &#39;class&#39; => &#39;common\components\FileTarget&#39;,
        // 日志等级
        &#39;levels&#39; => [&#39;error&#39;],
        // 被收集记录的额外数据
        &#39;logVars&#39; => [&#39;_GET&#39;, &#39;_POST&#39;, &#39;_FILES&#39;, &#39;_COOKIE&#39;, &#39;_SESSION&#39;,&#39;_SERVER&#39;],
        // 指定日志保存的文件名
        &#39;logFile&#39; => &#39;@app/runtime/logs/error/app.log&#39;,
        // 是否开启日志 (@app/runtime/logs/error/20151223_app.log)
        &#39;enableDatePrefix&#39; => true,
        &#39;maxFileSize&#39; => 1024 * 1,
        &#39;maxLogFiles&#39; => 100,
      ],
      /**
       * 警告级别日志:当某些期望之外的事情发生的时候,使用该方法。
       * 使用方法:Yii::warning()
       */
      [
        &#39;class&#39; => &#39;common\components\FileTarget&#39;,
        // 日志等级
        &#39;levels&#39; => [&#39;warning&#39;],
        // 被收集记录的额外数据
        &#39;logVars&#39; => [&#39;_GET&#39;, &#39;_POST&#39;, &#39;_FILES&#39;, &#39;_COOKIE&#39;, &#39;_SESSION&#39;,&#39;_SERVER&#39;],
        // 指定日志保存的文件名
        &#39;logFile&#39; => &#39;@app/runtime/logs/warning/app.log&#39;,
        // 是否开启日志 (@app/runtime/logs/warning/20151223_app.log)
        &#39;enableDatePrefix&#39; => true,
        &#39;maxFileSize&#39; => 1024 * 1,
        &#39;maxLogFiles&#39; => 100,
      ],
      /**
       * info 级别日志:在某些位置记录一些比较有用的信息的时候使用。
       * 使用方法:Yii::info()
       */
      [
        &#39;class&#39; => &#39;common\components\FileTarget&#39;,
        // 日志等级
        &#39;levels&#39; => [&#39;info&#39;],
        // 被收集记录的额外数据
        &#39;logVars&#39; => [&#39;_GET&#39;, &#39;_POST&#39;, &#39;_FILES&#39;, &#39;_COOKIE&#39;, &#39;_SESSION&#39;,&#39;_SERVER&#39;],
        // 指定日志保存的文件名
        &#39;logFile&#39; => &#39;@app/runtime/logs/info/app.log&#39;,
        // 是否开启日志 (@app/runtime/logs/info/20151223_app.log)
        &#39;enableDatePrefix&#39; => true,
        &#39;maxFileSize&#39; => 1024 * 1,
        &#39;maxLogFiles&#39; => 100,
      ],
      /**
       * trace 级别日志:记录关于某段代码运行的相关消息。主要是用于开发环境。
       * 使用方法:Yii::trace()
       */
      [
        &#39;class&#39; => &#39;common\components\FileTarget&#39;,
        // 日志等级
        &#39;levels&#39; => [&#39;trace&#39;],
        // 被收集记录的额外数据
        &#39;logVars&#39; => [&#39;_GET&#39;, &#39;_POST&#39;, &#39;_FILES&#39;, &#39;_COOKIE&#39;, &#39;_SESSION&#39;,&#39;_SERVER&#39;],
        // 指定日志保存的文件名
        &#39;logFile&#39; => &#39;@app/runtime/logs/trace/app.log&#39;,
        // 是否开启日志 (@app/runtime/logs/trace/20151223_app.log)
        &#39;enableDatePrefix&#39; => true,
        &#39;maxFileSize&#39; => 1024 * 1,
        &#39;maxLogFiles&#39; => 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:

  • 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(&#39;onFlush&#39;,array($this,&#39;collectLogs&#39;)); 
  Yii::app()->attachEventHandler(&#39;onEndRequest&#39;,array($this,&#39;processLogs&#39;));}

And defined in the CApplication::run() method:


 if($this->hasEventHandler(&#39;onEndRequest&#39;)) {
 $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)

First For filtering, refer to the logic in CFileLogRoute::collectLogs():

 $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:

&#39;preload&#39;=>array(&#39;log&#39;),
components => array(
       &#39;log&#39;=>array(
         &#39;class&#39;=>&#39;CLogRouter&#39;,
         &#39;routes&#39;=>array(
          array(
            &#39;class&#39;=>&#39;CFileLogRoute&#39;,
            &#39;levels&#39;=>&#39;error, warning,trace&#39;,
          ),
         )
        )
       )

定义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(&#39;onEndRequest&#39;)) {
  $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组件添加新的路由配置:

&#39;log&#39;=>array(
&#39;class&#39;=>&#39;CLogRouter&#39;,
&#39;routes&#39;=>array(
array(
&#39;class&#39;=>&#39;CFileLogRoute&#39;,
&#39;levels&#39;=>&#39;error, warning,trace&#39;,
),
array(
&#39;class&#39; => &#39;myEmailLogRoute&#39;,
&#39;levels&#39; => &#39;error&#39;, #所有异常的错误级别均为error, 
&#39;categories&#39; => &#39;exception.CDbException&#39;, #数据库产生错误时,均会产生CDbException异常。
&#39;host&#39; => &#39;mail.163.com&#39;,
&#39;port&#39; => 25,
&#39;user&#39; => &#39;jeff_yu&#39;,
&#39;password&#39; => &#39;you password&#39;,
&#39;timeout&#39; => 30,
&#39;emails&#39; => &#39;jeff_yu@gmail.com&#39;, #日志接收人。
&#39;sentFrom&#39; => &#39;jeff_yu@gmail.com&#39;,
),

经过以上处理,即可使之实现我们的目的,当然你可以根据自己的需要进一步扩展之。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Yii2框架实现数据库常用操作解析

关于yii2中结合gridview使用modal弹窗的代码

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools