Table of Contents
1. Information recording
2. Information routing
3. Message filtering
4. Record context information
5. 性能分析
6. SQL执行分析
Home Backend Development PHP Tutorial Yii Framework Official Tutorial Supplement 45 - Special Topic: Logging

Yii Framework Official Tutorial Supplement 45 - Special Topic: Logging

Feb 16, 2017 am 09:34 AM



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 recording

Information can be recorded 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);
Copy after login

When recording information, we need to specify its category and level. The category is a format similar to a path alias. String. 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 ordinary information.

  • Yii Framework Official Tutorial Supplement 45 - Special Topic: Logging: This is the performance overview (Yii Framework Official Tutorial Supplement 45 - Special Topic: Logging). 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 stored 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 information routing, for example, sending information 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 information 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'=>[email protected]',
                ),
            ),
        ),
    ),
)
Copy after login

In the above example, we define 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 starting with system. will be saved. The second route is CEmailLogRoute, which will send information to the specified email address, and only the level of error or warning will be sent.

In Yii, the following log routes are available:

  • CDbLogRoute: Save information to a database table.

  • CEmailLogRoute: Send information to the specified Email address.

  • CFileLogRoute: Saves information to a file in the application's runtime directory.

  • CWebLogRoute: Display information at the bottom of the current page.

  • CProfileLogRoute: Displays profiling information at the bottom of the page.

Information: Information routing occurs when the last onEndRequest event of the current request cycle is triggered. To explicitly terminate the current request process, please call CApplication::end() instead of using die() or exit(), because CApplication::end() will trigger the onEndRequest event so that the information will be recorded smoothly.

3. Message filtering

As we mentioned, messages can be filtered by their level and category before they are sent to a log router. This is done by setting the levels and categories attributes of the corresponding log route. Multiple levels or categories should be connected with commas.

Since the information classification is similar to xxx.yyy.zzz format, we can regard it as a classification level. Specifically, we say that xxx is the parent of xxx.yyy, which in turn is the parent of xxx.yyy.zzz. In this way, we can use xxx.* to represent category xxx and all its child and grandchild categories.

4. Record context information

Starting from version 1.0.6, we can set up to record additional context information, such as PHP predefined variables (such as $_GET, $_SERVER), session ID , username, etc. This is accomplished by specifying a suitable log filtering rule in the CLogRoute::filter attribute of a log route.

框架使用非常方面的可以用于大多数日志过滤的CLogFilter,默认情况下, CLogFilter 将会记录一条包含变量(如通常包含系统上下文变量值的如$_GET,$_SERVER等)的信息。CLogFilter还可以用于配置到每一个日志信息之前,带上session ID,用户名等。当我们要查找日志信息的位置时这将带来极大的便利 。

下面的配置展示了如何开启记录上下文信息。每一个日志路由都有自己的日志过滤器,但是默认情况下, 日志路由并不包含日志过滤器。


array(
    ......
    'preload'=>array('log'),
    'components'=>array(
        ......
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error',
                    'filter'=>'CLogFilter',
                ),
                ...other log routes...
            ),
        ),
    ),
)
Copy after login

从版本1.0.7开始,Yii支持记录通过调用Yii::trace返回的日志记录信息中的回调栈信息。这一特性默认是取消的,因为这回降低性能。想要使用这一特性,只需在入口脚本中定义一个名为YII_TRACE_LEVEL的大于0的常量 (在包含yii.php之前),然后Yii将会在每一个trace信息之后加上应用代码回调栈的文件名和行号。 YII_TRACE_LEVEL 决定了每一个回调栈的层级将会被记录。这个信息在开发期间很有用,因为这可以帮助我们确定触发trace信息的位置。

5. 性能分析

性能分析是一个特殊的日志记录类型。性能分析可以用于衡量指定代码块的运行时间,并且找出性能瓶颈。

使用性能分析,我们需要指定被分析的代码块。我们通过插入如下代码来标记每一个代码块的开始和结束:


Yii::beginProfile('blockID');
...code block being Yii Framework Official Tutorial Supplement 45 - Special Topic: Loggingd...
Yii::endProfile('blockID');
Copy after login

其中blockID 指的是代码块的唯一标志符.

注意, 代码块需要被合理嵌套。也就是说,一个代码块不能和另一代码块交叉嵌套:要么是并行的,要么是完全封闭包含在另一个代码块里。

为了显示分析结果, 需要安装 一个包含CProfileLogRoute日志路由的CLogRouter 应用组件。这和我们处理其他的信息路由一样,CProfileLogRoute路由将会在当前页面的底部显示性能分析结果。

Yii Framework Official Tutorial Supplement 45 - Special Topic: Logging

6. SQL执行分析

性能分析在处理数据库操作时尤为有用,因为 SQL 执行经常是一个应用主要的性能瓶颈。 我们当然可以在每一次SQL执行的地方插入beginProfile 和 endProfile语句, 从版本1.0.6开始, 但Yii 提供了一个更加系统的方式来解决这个问题。

通过在应用配置中设置 CDbConnection::enableProfiling 为true, 每一个被执行的SQL语句都会被分析. 结果可以通过设置前面提到的CProfileLogRoute来显示, 这样我们就能知晓每一个SQL语句的执行时间。除此之外我们还可以调用CDbConnection::getStats() 来取回SQL语句执行的次数和总的执行时间。

 以上就是Yii框架官方教程增补版45——专题:日志记录的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP development skills: How to implement website access logging function PHP development skills: How to implement website access logging function Sep 22, 2023 am 08:31 AM

PHP development skills: How to implement website access logging function During the development process of the website, we often need to record the website access log for subsequent analysis and debugging. This article will introduce how to use PHP to implement the website access logging function and provide specific code examples. 1. Create a log file First, we need to create a file to store the log. In PHP, you can use the file_put_contents() function to create files and write contents. Below is an example of creating a log file

Laravel development advice: How to handle exceptions and log records Laravel development advice: How to handle exceptions and log records Nov 23, 2023 am 10:08 AM

In Laravel development, exception handling and logging are very important parts, which can help us quickly locate problems and handle exceptions. This article will introduce how to handle exceptions and log records to help developers better develop Laravel. Exception handling Exception handling means catching the error and handling it accordingly when an error or unexpected situation occurs in the program. Laravel provides a wealth of exception handling mechanisms. Let's introduce the specific steps of exception handling. 1.1 Exception types in Larav

How to use Vue to implement server-side communication analysis and logging How to use Vue to implement server-side communication analysis and logging Aug 10, 2023 pm 02:58 PM

How to use Vue to implement parsing and logging of server-side communication In modern web applications, server-side communication is crucial for processing real-time data and interactivity. Vue is a popular JavaScript framework that provides a simple and flexible way to build user interfaces and process data. This article will explore how to use Vue to implement server-side communication and perform detailed analysis and logging. A common way to implement server-side communication is to use WebSockets. WebSo

ThinkPHP6 logging and debugging skills: quickly locate problems ThinkPHP6 logging and debugging skills: quickly locate problems Aug 13, 2023 pm 11:05 PM

ThinkPHP6 logging and debugging skills: quickly locate problems Introduction: In the development process, troubleshooting and solving problems is an inevitable part. Logging and debugging are one of our important tools for locating and solving problems. ThinkPHP6 provides rich logging and debugging functions. This article will introduce how to use these functions to quickly locate problems and speed up the development process. 1. Logging function configuration log is in the configuration file config/app.php of ThinkPHP6. We can find

How to implement request logging and analysis of web services through Nginx proxy server? How to implement request logging and analysis of web services through Nginx proxy server? Sep 06, 2023 pm 12:00 PM

How to implement request logging and analysis of web services through Nginx proxy server? Nginx is a high-performance open source web server and reverse proxy server with excellent performance and scalability. In practical applications, we usually need to record and analyze the request logs of web services in order to monitor and optimize system performance. This article will introduce how to implement request logging and analysis of web services through Nginx proxy server, and give corresponding code examples. Enable Nginx request log function

How to create a custom logging solution for your PHP website How to create a custom logging solution for your PHP website May 03, 2024 am 08:48 AM

There are several ways to create a custom logging solution for your PHP website, including: using a PSR-3 compatible library (such as Monolog, Log4php, PSR-3Logger) or using PHP native logging functions (such as error_log(), syslog( ), debug_print_backtrace()). Monitoring the behavior of your application and troubleshooting issues can be easily done using a custom logging solution, for example: Use Monolog to create a logger that logs messages to a disk file.

Optimizing program logging: Sharing tips on setting log4j log levels Optimizing program logging: Sharing tips on setting log4j log levels Feb 20, 2024 pm 02:27 PM

Optimizing program logging: Tips for setting log4j log levels Summary: Program logging plays a key role in troubleshooting, performance tuning, and system monitoring. This article will share tips on setting log4j log levels, including how to set different levels of logs and how to illustrate the setting process through code examples. Introduction: In software development, logging is a very important task. By recording key information during the running process of the program, it can help developers find out the cause of the problem and perform performance optimization and system monitoring.

How to perform error handling and logging in C++ class design? How to perform error handling and logging in C++ class design? Jun 02, 2024 am 09:45 AM

Error handling and logging in C++ class design include: Exception handling: catching and handling exceptions, using custom exception classes to provide specific error information. Error code: Use an integer or enumeration to represent the error condition and return it in the return value. Assertion: Verify pre- and post-conditions, and throw an exception if they are not met. C++ library logging: basic logging using std::cerr and std::clog. External logging libraries: Integrate third-party libraries for advanced features such as level filtering and log file rotation. Custom log class: Create your own log class, abstract the underlying mechanism, and provide a common interface to record different levels of information.

See all articles