search
HomeBackend DevelopmentPHP TutorialPHP development framework Yii Framework tutorial (3) Add logs to the application

In the process of developing applications, debugging is also a very important link. In addition to the real-time debugging supported by IDE (such as VS.PHP or the debugging function supported by IDE), adding appropriate debugging information to the web application is also very useful. Method, anyone who has developed Java or .Net applications is familiar with log4XX. Yii Framework also provides a similar Log function, Yii::log, which appears as a built-in component of CWebApplication. It can be configured through a configuration file (the configuration in Yii is usually protected/config/main.php).

The previous article Yii Framework Development Concise Tutorial (2) Yii Web Application Basics briefly describes the application components.

In addition to the Log component, Yii predefines a series of core application components to provide functions used in common web applications. For example, the request component is used to parse user requests and provide information such as URLs, cookies, etc. By configuring the properties of these core components, we can modify Yii's default behavior in almost all aspects.

Below we list the core components predefined by CWebApplication.

assetManager: CAssetManager - manages the release of private resource files.

authManager: CAuthManager - Manages role-based access control (RBAC).

cache: CCache - Provides data caching function. Note that you must specify the actual class (eg CMemCache, CDbCache). Otherwise, NULL will be returned when you access this component.

clientScript: CClientScript - Manages client-side scripts (javascripts and CSS).

coreMessages: CPhpMessageSource - Provides translation of core messages used by the Yii framework.

db: CDbConnection - Provides database connection. Note that to use this component you must configure its connectionString property.

errorHandler: CErrorHandler - Handles uncaught PHP errors and exceptions.

format: CFormatter - formatted numerical display. This feature is available starting with version 1.1.0.

messages: CPhpMessageSource - Provides message translations used in Yii applications.

request: CHttpRequest - Provides information about the user's request.

securityManager: CSecurityManager - Provides security-related services, such as hashing, encryption.

session: CHttpSession - Provides session-related functions.

statePersister: CStatePersister - Provides global state persistence methods.

urlManager: CUrlManager - Provides URL parsing and creation related functions

user: CWebUser - Provides identification information of the current user.

themeManager: CThemeManager - manages themes. These components will be introduced step by step in subsequent tutorials. The basic method of using the Log function is given below: Here we modify the Yii Framework Development Concise Tutorial (1) The first application is Hello World. Add a log to it. 1. Create the configuration file protected/config/main.php. If you want to write the log to a file, you can use the following configuration:

// This is the main Web application configuration. Any writable// CWebApplication properties can be configured here.return array(
// preloading 'log' component'preload'=>array('log'),
// application components'components'=>array(
'log'=>array('class'=>'CLogRouter','routes'=>array(array('class'=>'CFileLogRoute','levels'=>'info,error, warning',),
),),),
);

CLogRouter 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 files or emails. This is called information routing.

Generally when using the Log function, you need to preload the Log component, which is configured through preload. Preload allows the application to load some modules in advance. Tip: By default, application components are created as needed . This means that a component will only be created if it is accessed. Therefore, the overall performance of the system will not be degraded due to the configuration of many components. Some application components (such as CLogRouter) are created whether they are used or not. In this case, we list the IDs of these components in the application's configuration file: preload.

2. Modify the entry script index.php and configure the main application instance to use the newly created configuration file.

$yii='C:/yiiframework/yii.php';
// remove the following line when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
$config=dirname(__FILE__).'/protected/config/main.php';
require_once($yii);
Yii::createWebApplication($config)->run();3. 创建protected/runtime

Because the default directory where log files are written is protected/runtime, the runtime directory must be created in advance, otherwise Yii will display the log directly on the web page.

4. In this way, you can use Yii::log or Yii::trace to add logs to the application.

The difference is that the latter only records information when the application is running in debug mode.

Yii::log($message, $level, $category);
Yii::trace($message, $category);

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

profile: This is the performance overview (profile). More detailed instructions will follow shortly.

warning: This is used for warning information.

error: This is used for fatal error messages.

Yii's logs are classified and filtered by Level and Category. As we mentioned, multiple levels or categories should be connected with commas.

由于 信息分类是类似 xxx.yyy.zzz 格式的,我们可以将其视为一个分类层级。 具体地,我们说 xxx 是 xxx.yyy 的父级,而 xxx.yyy 又是 xxx.yyy.zzz 的父级。 这样我们就可以使用 xxx.* 表示分类 xxx 及其所有的子级和孙级分类。

有了以 上知识,我们修改SiteController的actionIndex,添加一行日志。

public function actionIndex()
{
Yii::log("action","info","site.action");
$this->render("index");
}

5. 运行应用,可以看到Yii在protected/runtime 创建了一个application.log

其内容如下:

2012/12/11 21:23:38 [info] [site.action] action

注: 日志存放的位置和文件名都可以通过配置来修改,一般情 况使用缺省值就可以了,和log4X 类似,应用的日志可以通过路由同时写到多个目的地(文件,Email等)这些多可以通过配置 来实现,具体可以参见日志记录。

以上就是PHP开发框架Yii Framework教程(3) 为应用添加日志的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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 create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools