Home PHP Framework YII Logging system in Yii framework: recording application events

Logging system in Yii framework: recording application events

Jun 21, 2023 pm 03:42 PM
event log yii framework

In the Yii framework, there is a complete logging system that can record application events so that developers can conduct debugging and performance analysis. This article will introduce the basic use of the logging system in the Yii framework and some practical techniques.

  1. Configuring the log component

The Yii framework uses files as the log storage method by default, and you can configure the log component in the configuration file. The following is a simple configuration example:

'log' => [
    'traceLevel' => YII_DEBUG ? 3 : 0,
    'targets' => [
        [
            'class' => 'yiilogFileTarget',
            'levels' => ['error', 'warning'],
            'logFile' => '@runtime/logs/app.log',
        ],
    ],
],
Copy after login

Among them, traceLevel refers to the log level recorded by the Yii framework in debug mode. The higher the level, the more information is recorded. detailed. targets is an array that can configure multiple log targets. In this example, there is only one target, which is to write error and warning level logs@ runtime/logs/app.log file.

  1. Record log information

It is very simple to record log information in the code. You can use the shortcut function provided by the Yii framework, for example:

Yii::info('This is an info message.');
Yii::warning('This is a warning message.');
Yii::error('This is an error message.');
Copy after login

Shortcut function , info, warning and error respectively correspond to the three levels of the log. You can choose to use it according to the situation.

When recording logs, in addition to directly recording strings, you can also use replaceable data, represented by the placeholder {}. For example:

Yii::info('User {username} registered successfully.', ['username' => 'John']);
Copy after login

At this time, {username} will be replaced with 'John'. The advantage of this is that the log information is more detailed and easier to troubleshoot problems.

  1. Using context information

The logging system of the Yii framework supports using context information to record more detailed log information. Context information includes some additional data, such as current user information, request parameters, etc. When recording logs, you can add contextual information by setting the $context parameter, for example:

Yii::warning('Invalid user input', ['category' => 'appcontrollersMyController', 'action' => 'create', 'params' => $_POST]);
Copy after login

In the above code, we use 3 contextual information, which are the controllers to which they belong. Class, requested method and request parameters. This will provide a clearer understanding of where the logs occur and the specific request information.

  1. Filtering and classification

In actual applications, we may not want to record all log information. The logging system of the Yii framework provides a filtering and classification mechanism that can filter and classify log messages based on conditions.

In the configuration, you can set the categories attribute to classify log messages, for example:

'log' => [
    'targets' => [
        [
            'class' => 'yiilogFileTarget',
            'categories' => ['appcontrollersMyController'],
            'logFile' => '@runtime/logs/mycontroller.log',
        ],
    ],
],
Copy after login

In the above configuration, we only log messages from appcontrollersMyController Controller's log information and write them to the @runtime/logs/mycontroller.log file.

In addition to classification, we can also use functions to filter log messages, for example:

'log' => [
    'targets' => [
        [
            'class' => 'yiilogFileTarget',
            'levels' => ['error'],
            'logFile' => '@runtime/logs/app.log',
            'logVars' => [],
            'except' => [
                'yiiwebHttpException:404',
            ],
        ],
    ],
],
Copy after login

In the above configuration, we only record error level log information, and at the same time All contextual information is ignored. We use the except attribute to specify log messages to ignore. In this example, we ignore all 404 error messages.

  1. Customized log target

The logging system of the Yii framework allows us to customize the log target, such as sending log messages to email, databases or third-party log services, etc. . When we need to customize the log target, we need to inherit the yiilogTarget class and implement the export method. For example:

class EmailTarget extends yiilogTarget
{
    public $to;

    public function export()
    {
        foreach ($this->messages as $message) {
            mail($this->to, $message[0], $message[1]);
        }
    }
}
Copy after login

In the above code, we define a custom email target and implement the export method. In the export method, we use the mail function to send the log message to the specified mailbox.

In practical applications, we can write different log targets as needed to meet different log storage requirements.

Summary

The logging system of the Yii framework is a very practical component that can help developers track application events for better debugging and performance analysis. When using the logging system, we need to understand the basic configuration and usage, as well as some practical tips, such as using contextual information, classification and filtering, customizing log targets, and so on. Only by in-depth understanding and flexible use of the log system can we better solve log problems and improve the quality and performance of applications.

The above is the detailed content of Logging system in Yii framework: recording application events. For more information, please follow other related articles on the PHP Chinese website!

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)

What is event ID 6013 in win10? What is event ID 6013 in win10? Jan 09, 2024 am 10:09 AM

The logs of win10 can help users understand the system usage in detail. Many users must have encountered log 6013 when looking for their own management logs. So what does this code mean? Let’s introduce it below. What is win10 log 6013: 1. This is a normal log. The information in this log does not mean that your computer has been restarted, but it indicates how long the system has been running since the last startup. This log will appear once every day at 12 o'clock sharp. How to check how long the system has been running? You can enter systeminfo in cmd. There is one line in it.

Troubleshooting Event 7034 Error Log Issues in Win10 Troubleshooting Event 7034 Error Log Issues in Win10 Jan 11, 2024 pm 02:06 PM

The logs of win10 can help users understand the system usage in detail. Many users must have seen a lot of error logs when looking for their own management logs. So how to solve them? Let’s take a look below. . How to solve win10 log event 7034: 1. Click "Start" to open "Control Panel" 2. Find "Administrative Tools" 3. Click "Services" 4. Find HDZBCommServiceForV2.0, right-click "Stop Service" and change it to "Manual Start "

Get upcoming calendar events on your iPhone lock screen Get upcoming calendar events on your iPhone lock screen Dec 01, 2023 pm 02:21 PM

On iPhones running iOS 16 or later, you can display upcoming calendar events directly on the lock screen. Read on to find out how it's done. Thanks to watch face complications, many Apple Watch users are used to being able to glance at their wrist to see the next upcoming calendar event. With the advent of iOS16 and lock screen widgets, you can view the same calendar event information directly on your iPhone without even unlocking the device. The Calendar Lock Screen widget comes in two flavors, allowing you to track the time of the next upcoming event, or use a larger widget that displays event names and their times. To start adding widgets, unlock your iPhone using Face ID or Touch ID, press and hold

How to view your medication log history in the Health app on iPhone How to view your medication log history in the Health app on iPhone Nov 29, 2023 pm 08:46 PM

iPhone lets you add medications to the Health app to track and manage the medications, vitamins and supplements you take every day. You can then log medications you've taken or skipped when you receive a notification on your device. After you log your medications, you can see how often you took or skipped them to help you track your health. In this post, we will guide you to view the log history of selected medications in the Health app on iPhone. A short guide on how to view your medication log history in the Health App: Go to the Health App>Browse>Medications>Medications>Select a Medication>Options&a

Detailed explanation of log viewing command in Linux system! Detailed explanation of log viewing command in Linux system! Mar 06, 2024 pm 03:55 PM

In Linux systems, you can use the following command to view the contents of the log file: tail command: The tail command is used to display the content at the end of the log file. It is a common command to view the latest log information. tail [option] [file name] Commonly used options include: -n: Specify the number of lines to be displayed, the default is 10 lines. -f: Monitor the file content in real time and automatically display the new content when the file is updated. Example: tail-n20logfile.txt#Display the last 20 lines of the logfile.txt file tail-flogfile.txt#Monitor the updated content of the logfile.txt file in real time head command: The head command is used to display the beginning of the log file

How to implement change event binding of select elements in jQuery How to implement change event binding of select elements in jQuery Feb 23, 2024 pm 01:12 PM

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

Different types of Linux log files and setting steps Different types of Linux log files and setting steps Feb 26, 2024 pm 10:54 PM

Types of Linux log files and configuration methods In Linux systems, log files are very important. They record the running status of the system, user operations, and the occurrence of various events. By checking log files, system administrators can discover problems in time and handle them accordingly. This article will introduce the common types of log files in Linux systems and how to configure logging. 1. Types of log files System log: System log is a log file that records the operating status of the system, including system startup, shutdown, service startup and stop, etc.

Understand the meaning of event ID455 in win10 logs Understand the meaning of event ID455 in win10 logs Jan 12, 2024 pm 09:45 PM

The logs of win10 have a lot of rich content. Many users must have seen the event ID455 display error when looking for their own management logs. So what does it mean? Let’s take a look below. What is event ID455 in the win10 log: 1. ID455 is the error <error> that occurred in <file> when the information store opened the log file.

See all articles