[Yii series] error handling and log system, and yii series processing logs

Source: Internet
Author: User

[Yii series] error handling and log system, and yii series processing logs
Origin

Follow the steps in the previous chapter. In the previous chapter, we mainly explain some knowledge points about user requests, resolution requests, server feedback requests, and sessions, it is inevitable that you will encounter some problems, such as database query failure, Script Error Caused by user input, network problems, and so on. For emergencies, we generally know that we have used software, there will be error processing and logging to record this process. Similarly, Yii provides similar functions to help us capture errors, record errors, and handle corresponding errors.

Error Handling

Yii has a built-in error handler error processor.

All non-fatal PHP errors (for example, warnings, and prompts) are converted to retriable exceptions.

Throw an exception

use yii\web\NotFoundHttpException;throw new NotFoundHttpException();

If exceptions may occur, try... catch...

use Yii;use yii\base\ErrorException;try {    10/0;} catch (ErrorException $e) {    Yii::warning("Division by zero.");}

The error handler error processor is enabled by default.

return [    'components' => [        'errorHandler' => [            'errorAction' => 'site/error',        ],    ]];

Generally, you only need to retain the configurations in the original application body. If you want to customize the output of incorrect formats, you can go to the official website to study them carefully. If you want to do so, click "generate error" and print it out, as for how to record and facilitate our search, this is important.

Log System

When talking about the log system, everyone may first think of inserting a line of code in a proper position, and then executing this line of code will be recorded into a file.

Yes, this is the most primitive log system. The logging system that used to issue Python automatic mail is such a simple thing, but it will be very effective. Just like writing comments to programmers, adding a log to the correct location will greatly reduce the maintenance cost of your system.

Yii provides a powerful log framework that is highly customizable and scalable.

It is also quite simple to call.

Yii: trace (): records a message to track how a piece of code runs. This is mainly used during development. Yii: info (): record a message to convey some useful information. Yii: warning (): records a warning message to indicate exceptions that have occurred. Yii: error (): records a fatal error, which should be checked as soon as possible.

The preceding log types are recorded based on the severity.

Exception must be recorded in warning and error.

Important log information is recorded separately in a separate key for easy search, which is the second parameter of these methods: category, which can be customized. This is related to your configuration. The following is a standard log configuration method.

return [    // the "log" component must be loaded during bootstrapping time    'bootstrap' => ['log'],        'components' => [        'log' => [            'targets' => [                [                    'class' => 'yii\log\DbTarget',                    'levels' => ['error', 'warning'],                ],                [                    'class' => 'yii\log\EmailTarget',                    'levels' => ['error'],                    'categories' => ['yii\db\*'],                    'message' => [                       'from' => ['log@example.com'],                       'to' => ['admin@example.com', 'developer@example.com'],                       'subject' => 'Database errors at example.com',                    ],                ],            ],        ],    ],];

logThe component must be loaded during bootstrapping so that it can schedule log messages to the target in time.

The above error and warning will be stored in the form of data tables. I usually store them under the runtime log and store them as files. After one week, I will back up these logs, delete these logs from the server.

When the second is error, an email is sent to example.com and admin and developer respectively.

Yii is equipped with the following built-in log targets.

Yii \ log \ DbTarget: stores log messages in the database table. Yii \ log \ EmailTarget: sends log messages to the specified email address. Yii \ log \ FileTarget: Save the log message to the file. yii \ log \ SyslogTarget: Save the log message to the system log by calling the PHP function syslog.

I usually use the FileTarget. The configuration is as follows:

'log' => [        'traceLevel' => YII_DEBUG ? 3 : 0,        'targets' => [            [                'class' => 'yii\log\FileTarget',                'levels' => ['error', 'warning'],            ],            [                'class' => 'yii\log\FileTarget',                'categories' => ['tongzi.info.*', 'yii\db\*'],                'levels' => ['info'],                'logVars' => [],            ]        ],    ]

The preceding application configuration sets the yii \ log \ Dispatcher: traceLevel level. IfYII_DEBUGIf it is enabled, it is 3; otherwise, it is 0.

This means that ifYII_DEBUGWhen enabled, each log message is appended with a maximum of three call stack levels when the log message is recorded.YII_DEBUGOtherwise, no call stack information is included.

The categories attribute is an array containing the message category name or pattern.

A classification mode is a star*Prefix of the ending category name. If a category name has the same prefix as the category name, the category name matches the category name.

Message format

If you use the log targets of the yii \ log \ FileTarget class, your message format should be the following ~

2014-10-04 18:10:15 [::1][][-][trace][yii\base\Module::getModule] Loading module: debug

By default, log messages are formatted in the following format: yii \ log \ Target: formatMessage ():

Timestamp [IP address][User ID][Session ID][Severity Level][Category] Message Text

You can also customize the log format, but there is no need to do that. So much information is enough to check for errors.

In addition, after defining each category, you can use various tools to view logs.

We recommend that you use two log analysis tools, splunk, log ease, and splunk. I have a student here to make a big data analysis algorithm. Anyway, I think it's awesome, splunk is second to none in global big data analysis. The interface is also friendly, but the free version only has MB space for you to use. This is a huge pitfall.

Another one is log ease, which is also the log analysis tool I am currently using. It is a good tool in China. You can go to his official website to study and engage in things.

Now, I will talk about error handling and log system today. ^_^

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.