In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the PHP Yii framework commonly used log operation example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
Journal
Yii provides a highly customized and scalable logging framework. Depending on the usage scenario, you can easily record, filter, and merge all kinds of messages, such as text files, database files, and emails.
The logging framework that uses Yii includes the following steps:
Call the logging method
Configure log filtering and export settings in the configuration file of the main application (such as web.php under basic)
Check the filtered log information in different scenarios
Keep a log
Logging is actually a simple call to the following method:
[[Yii::trace ()]]: records messages about the running of a piece of code. Mainly used in the development environment.
[[Yii::info ()]]: used when recording some useful information in some places.
[[Yii::warning ()]]: use this method when something unexpected happens.
[[Yii::error ()]]: when some fatal problem occurs that needs to be solved immediately, call this method to record the relevant information.
The above methods record information based on different level and types, but they actually call the same method function ($message, $category = 'application'). Where $message is the information to be recorded, and $category represents the attribution class of the log. The following code indicates that a message of type trace is recorded under the default 'application' category.
Yii::trace ('start calculating average revenue')
Tip: the recorded $message can be a simple string or a complex array or object. You should choose the appropriate $message type according to the logging responsibilities in different scenarios. By default, if the $message you record is not String, the log will call the [[yii\ helpers\ VarDumper::export ()]] method to output a message of type string when exporting.
In order to better organize and manage and filter log messages, you should usually assign appropriate categories to each type of log. You can choose a category with obvious hierarchical meaning to facilitate the screening of different categories of logs according to different purposes. A simple and effective naming method is to use PHP's magic constant METHOD as the name of the category. This is what the core code in the Yii framework does when logging. For example:
Yii::trace ('start calculating average revenue', _ _ METHOD__)
Where there is a constant METHOD, it represents the name of the current method (with the full prefix of the class to which the current method belongs). For example, if there is the above line of code in the calculate method in the class app\ controllers\ RevenueController, then the METHOD represents' app\ controllers\ RevenueController::calculate'.
Tip: the method mentioned above is actually a simple use of the [[yii\ log\ Logger::log () | log ()]] method of the singleton object [[yii\ log\ Logger::log () | log ()]], which can be obtained by the Yii::getLogger () method. When we have recorded enough log information or the current application is finished, the log object will call the [yii\ log\ Dispatcher | message dispatcher] method to write the recorded log information to the destination of the configuration.
Log targets
A log target is an instance of [[yii\ log\ Target]] or its subclass. It filters the logs according to the severity level and classification, and then exports the logs to the appropriate media. For example, a [[yii\ log\ DbTarget | database target]] object exports the filtered log information to the corresponding database.
You can register multiple log targets at the logging component in the configuration file of the application, like the following:
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',],]
Note: the logging component must be configured in bootstrap so that log information can be distributed to the corresponding log target.
In the above code, two log target are registered in [[yii\ log\ Dispatcher::targets]].
The first one filters out errors and warnings and saves them to the database.
The second filters out error messages that start with yii\ db* and emails them to admin@example.com and developer@example.com.
Yii has the following built-in log targets, and you can refer to the API documentation to learn how to configure and use them.
[[yii\ log\ DbTarget]]: save the log information to the database.
[[yii\ log\ EmailTarget]]: sends log information to the specified mailbox, as shown in the above example.
[[yii\ log\ FileTarget]]: write the log to a file.
[[yii\ log\ SyslogTarget]]: call the syslog () method of PHP to write the log to the system log.
Next, let's take a look at the common features of log target.
Message filtering
For each log target, you can configure its [[yii\ log\ Target::levels | levels]] and [[yii\ log\ Target::categories | categories]] attribute classes to set its severity and classification.
The [[yii\ log\ Target::levels | levels]] attribute takes one or more values in an array that contains the following values:
Error: messages recorded in [[Yii::error ()]]
Warning: messages recorded in [[Yii::warning ()]]
Info: the information recorded in [[Yii::info ()]]
Trace: corresponds to the information recorded in [[Yii::trace ()]].
Profile: corresponds to the information recorded in [[Yii::beginProfile ()]] and [[Yii::endProfile ()]]. In this way, more details are recorded below.
If you do not specify a value for [[yii\ log\ Target::levels | levels]], then any level information will be recorded.
The value of the [[yii\ log\ Target::categories | categories]] attribute is an array, where the value can be a specific category name or a regular-like matching pattern. Target will process these messages only if he can find the corresponding category name in this array or match a matching pattern. The matching pattern here consists of adding a number to the name of the category. If the classification happens to match the character in front of the sign of the matching pattern, then the classification finds the corresponding matching value. For example, the yii\ db\ Command::execute and yii\ db\ Command:: query methods in the class [[yii\ db\ Command]] use the class name class to record the relevant log information, so they all match the pattern yii\ db* at this time.
Similarly, if we do not specify [[yii\ log\ Target::categories | categories]], the log information for each category will be processed.
In addition to setting the whitelist of the category through the [[yii\ log\ Target::categories | categories]] attribute, you can also set the blacklist of the category through the [[yii\ log\ Target::except | except]] attribute. Classified log information that belongs to the blacklist will not be processed by target.
The following configuration specifies a category that matches yii\ db* or yii\ web\ HttpException:*, but does not include yii\ web\ HttpException:404, and it only handles log messages for errors and warnings.
['class' = >' yii\ log\ FileTarget','levels' = > ['error',' warning'], 'categories' = > [' yii\ db\ *', 'yii\ web\ HttpException:*',],' except' = > ['yii\ web\ HttpException:404',],]
Note: when the error handle catches the exception of HTTP, the log information will be recorded in the format of yii\ web\ HttpException:ErrorCode
Records, such as [[yii\ web\ NotFoundHttpException]], are recorded as yii\ web\ HttpException:404
Message formatting
Log targets exports logs in a variety of formats. For example, if your log target is [[yii\ log\ FileTarget]], then when you log in your program, you should find the following information similar to the file runtime/log/app.log:
2014-10-04 18:10:15 [:: 1] [] [-] [trace] [yii\ base\ Module::getModule] Loading module: debug
By default, [[yii\ log\ Target::formatMessage ()]]: will help us format the log information into the following format:
Timestamp [IP address] [User ID] [Session ID] [Severity Level] [Category] Message Text
You can customize the log prefix by configuring a custom callback function for the [[yii\ log\ Target::prefix]] property. The following code adds the user's ID (ip address, sessionId and other sensitive information is removed because of privacy) in front of each log message.
['class' = >' yii\ log\ FileTarget','prefix' = > function ($message) {$user = Yii::$app- > has ('user', true)? Yii::$app- > get ('user'): null; $userID = $user? $user- > getId (false):' -'; return "[$userID]";}]
In addition to the prefix of the log message, the log's target appends some context information to each batch of log records. By default, the global PHP variable contains $_ GET, $_ POST, $_ FILES, $_ COOKIE, $_ SESSION, and $_ SERVER. You can adjust the global variables of logging by configuring [[yii\ log\ Target::logVars]]. The following code indicates that only the variables related to $_ SERVER are recorded.
['class' = >' yii\ log\ FileTarget','logVars' = > ['_ SERVER'],]
When 'logVars' is empty, the relevant context information is not recorded. If you want to customize the way the context information is provided, you can override the [[yii\ log\ Target::getContextMessage ()]] method.
The trace level of the message
In the process of development, we always expect to know where each log message comes from. You can do this in Yii by configuring the [[yii\ log\ Dispatcher::traceLevel | traceLevel]] attribute. Examples of configurations are as follows:
Return ['bootstrap' = > [' log'], 'components' = > [' log' = > ['traceLevel' = > YII_DEBUG? 3: 0,' targets' = > [...],],]
The above example sets [[yii\ log\ Dispatcher::traceLevel | traceLevel]] to 3 and vice versa to 0 when YII_DEBUG is true. What does it mean? 3 means that each log record records the related three-layer stack call information, and 0 means that no related stack call information is recorded.
Tip: it is not necessary to always record the stack information of the call, which consumes performance. Therefore, you should only use this feature when you are developing or for debugging.
Emptying and export of messages
As mentioned above, the recorded messages are stored as an array in [[yii\ log\ Logger | logger object]]. In order to limit the excessive memory consumption of this array, when the content size of the array reaches a certain amount, it will be transferred from memory to the corresponding target (file, database...) by the corresponding target. You can determine the size of the quantity by setting the value of [yii\ log\ Dispatcher::flushInterval | flushInterval]. Like this:
Return ['bootstrap' = > [' log'], 'components' = > [' log' = > ['flushInterval' = > 100, / / default is 1000' targets' = > [...],],]
Note: memory is also refreshed at the end of the application run, so that the log target can record complete information.
The action of brushing log information from memory to the corresponding storage place does not happen immediately. In fact, as above, it only happens when the log size in memory reaches a certain level. You can modify it by configuring [[yii\ log\ Target::exportInterval | exportInterval]] values of different target, as in the following example:
['class' = >' yii\ log\ FileTarget','exportInterval' = > 100, / / default is 1000]
By default, you will not see log messages immediately under log target when you call Yii::trace () or other logging methods because of the empty and exported settings. This is a problem for some long-running console programs. However, this problem can be solved. Enter the following code. You need to set the values of [[yii\ log\ Dispatcher::flushInterval | flushInterval]] and [[yii\ log\ Target::exportInterval | exportInterval]] to 1:
Return ['bootstrap' = > [' log'], 'components' = > [' log' = > ['flushInterval' = > 1,' targets' = > ['class' = >' yii\ log\ FileTarget', 'exportInterval' = > 1,]
Note: emptying and exporting log messages so frequently can degrade system performance.
Toggle targets of logs
You can disable the target of logs by setting the [[yii\ log\ Target::enabled | enabled]] attribute. As described in the following code:
Yii::$app- > log- > targets ['file']-> enabled = false
The above code requires you to have the following configuration in the configuration file:
Return ['bootstrap' = > [' log'], 'components' = > [' log' = > ['targets' = > [' file' = > ['class' = >' yii\ log\ FileTarget',], 'db' = > [' class' = > 'yii\ log\ DbTarget',],]
Create a new target
First, it's easy to create a new log target. The main thing you do is to implement the [[yii\ log\ Target::export ()]] method and send the array type message [[yii\ log\ Target::messages]] to the specified storage medium. In the process, you can call the [[yii\ log\ Target::formatMessage ()]] method to format each log message. For more details, you can find more details in the Yiid distribution.
Performance evaluation
Performance evaluation is a special kind of logging. It is usually used to get data about the execution time of some modules in order to find out where the performance problem lies. For example, [[yii\ db\ Command]] this class uses the performance evaluation log to get the time spent on each sql query.
To use this type of log, the first thing you need to do is to determine the scope of the code you want to test. Then you should keep them closed between each piece of code, like this:
\ Yii::beginProfile ('myBenchmark');... code block being profiled...\ Yii::endProfile (' myBenchmark')
MyBenchmark is just a logo that allows you to quickly locate when you view the corresponding log records.
You can re-nest between beginProfile and endProfile, but you must ensure a correct closed relationship, as follows:
\ Yii::beginProfile ('block1'); / / some code to be profiled\ Yii::beginProfile (' block2'); / / some other code to be profiled\ Yii::endProfile ('block2');\ Yii::endProfile (' block1')
If the above closed relationship goes wrong, the corresponding records will not work properly.
For each piece of code being evaluated, the level of the log is profile. You can configure this information in the target of the log and export it. Yii has built-in Yii debugger to show the results of the evaluation.
The above is all the contents of the article "sample Analysis of Common Log Operations of the Yii Framework in PHP". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.