The article comes from the company's Daniel
1 Use of log
No matter what programming language is used, log output is almost everywhere. To sum up, there are several uses for the log:
L Problem tracking: Through the log not only includes some of our program bugs, can also be installed in the configuration, through the log can find problems.
L State Monitoring: Through real-time analysis of the log, you can monitor the operation of the system, so that early detection problems, early processing problems.
L Security Audit: Audit is mainly reflected in security, through the analysis of the log, you can find out whether there is unauthorized operation. 2 Basic Principles for log logs 2.1 Level division of the log
Java logs can usually be divided into: error, warn, info, debug, trace five levels. There are more predefined levels in J2SE, respectively: SEVERE, WARNING, INFO, CONFIG, FINE, Finer, FINEST. The correspondence of the two is roughly as follows:
log4j, slf4j |
j2se |
Use scenario |
Error |
SEVERE |
Problem has affected the software's normal operation Line, and the software cannot restore itself to its normal running state, you need to output the error log at that level. |
Warn |
WARNING |
Failure related to business process, this failure does not affect the next business execution, the usual result Input to the external cannot get the desired result. |
Info, |
Info |
System run state changes during system run, or key business process records for users or administrators in the Department Some information of concern during the operation of the EC. |
CONFIG |
System configuration, System run environment information, help install the implementation personnel to check the configuration is correct. |
debug |
FINE |
Software debugging information, developers using this level of log discovery program running some problems, platoon Except the fault. The |
Finer |
is basically ditto, but the information displayed is more detailed. |
Trace |
FINEST |
are mostly ditto, but the information displayed is more detailed. |
2.2 Log impact on performance
No matter how good the log tool is, there is always a more or less effect on the performance of the log output, in order to minimize the impact, there are several guidelines to follow:
How to create a logger instance: whether there is a static difference in the creation of a logger instance, in an earlier version of Log4j, which is generally required to use static, and in the high and later slf4j, the problem has been optimized, and the cost of getting (creating) logger instances is already low. So we want to: for the foreseeable majority of cases, a single instance of the class, you can not add a static prefix, for possibly many cases, especially the need for frequent creation of class, we require to add a static prefix .
L Judge Log level:
N for predictable log output that can occur frequently, such as for, while loop, and regularly executed jobs, it is recommended to use if to determine the logging level before outputting.
n the log level needs to be judged when the log output requires complex serialization, or when some of the output information is expensive to obtain. For example, the log needs to output the user name, and the user name needs to be in the log output from the database, this time you need to determine the log level to see if it is necessary to obtain this information.
L Prioritize the use of parameters to reduce string concatenation: Using parameters to output log information helps to strike a balance between performance and code simplicity. When the log level restricts output, the parameter content will not fuse into the final output, reducing the concatenation of strings, thereby enhancing execution efficiency. 2.3 When output log
The more the log is not the more detailed it is the better. In the analysis of the run log, look up the problem, we often encounter the log did not, useless log a large pile, or the effective log is a lot of meaningless log information submerged, it is very difficult to find. So when do I output the log? The following is a list of common cases where you need to output logs, and the level of the log is basically >=info, and the debug level log usage scenario is not specifically listed in this section and needs to be specifically analyzed, but it is also "appropriate", not the more the better. 2.3.1 System startup parameters, environment variables
System start-up parameters, configuration, environment variables, system.properties and other information for the normal operation of the software is essential, the output of this information to help install the configuration of the log quickly through the problem, so the program is necessary in the start-up process to use the key parameters, variables in the log output. In the output, it is necessary to note that not all the output of the brain, but the software involved in the operation of the configuration information output. For example, if the software is sensitive to the memory parameters of the JVM and requires a minimum configuration, then the values of the-xms-xmx-xx:permsize parameters in the log will need to be exported. 2.3.2 Exception Capture Office
In the capture anomaly output log, we can do in the basic, the only need to pay attention to is how to output a simple and clear log information. This is further explained in the following question. when the 2.3.3 function gets the desired result
A function, especially a function for external system or remote invocation, usually has a desired result, but if the internal system or output parameter is wrong, the function will not return the expected correct result, then the log is required, and the log is generally warn. What needs to be noted here is that the result is not that there is no return without the need to log, or that returning false requires logging. For example, function: Isxxxxx (), regardless of return true, false log is not required, but if the system can not determine whether it should return true or FALSE, you need to log, and the level of the log should be at least warn. 2.3.4 Key Operations
The log of key operations is generally the info level, and you can consider using the debug level if the number and frequency are high. Here are some examples of key operations, and the actual key operations must be more than that.
N Delete: Delete a file, delete a group of important database records ...
N Add: When interacting with an external system, a file is received, a task is received ...
N Processing: Start, end a task ...
N...... 2.4 Contents of log output
L Error: A short description of the error, the key parameter associated with the error, and if there is an exception, have the StackTrace of the exception.
L WARN: A short description of the alarm, and the key parameter associated with the error, if there is an exception, to have the exception of the StackTrace.
L Info: Concise Description of information, if there are relevant dynamic key data, to be output together, such as the relevant ID, name and so on.
L DEBUG: Simple description, related data, if there is an exception, to have the exception of the StackTrace.
in the log-related data output should pay special attention to the protection of sensitive information, such as password changes, can not output the password to the log. 2.5 When to use J2SE's own log
We usually use the SLF4J or log4j tools to log logs, so we also need to use the J2SE log frame. Of course, in order to reduce the reliance on third party jar packages when we write some generic tool classes, we first consider using java.util.logging.
Considering that the SLF4J log framework provides the Log Bridge tool, For Java.util.logging provides a handler, so the common application development process can also consider the use of J2SE own log, so that not only can reduce the compilation of project dependencies, while the application implementation can be more flexible to choose the Log Output tool pack.
3 Analysis of typical problems 3.1 The place to use the log is not
It is obviously problematic to use e.printstacktrace () directly on the handling of exceptions above, and the correct approach is to either output the error message by log or throw an exception directly, or create a new custom exception to throw.
another: For static tool class functions in the exception handling, the simplest way is not to capture, not log, directly up, if you think the exception type too much, or ambiguous meaning, you can throw the custom exception class instance.
3.2 long-winded repetition, no focus
First of all, there should be no error level log.
Second, the direct output of e.tostring () in the log provides too little information for locating problems.
Also need to be clear: the log system is a multi-threaded public system, between the two rows of log output may be inserted into other threads of logging, will not be in the order we intend to output, followed by a more typical example.
Finally, the above log can be simplified to:
Logger.debug ("From Properties ...) {}... {} ... ", name, value, e);
Logger.warn ("Get {} from Properties error: {}", name, e.tostring ());
Or a direct sentence:
Logger.warn ("From Properties ...) {}... {} ... ", name, value, e);
or more perfect:
if (logger.isdebugenabled ()) {
Logger.warn ("From Properties ...) {} ... ", name, E);
}else{
Logger.warn ("Get {} from Properties error: {}", name, e.tostring ());
}
3.3 The relationship between log and exception handling
First, the above log information is not sufficient, the level definition is not appropriate.
In addition, since the log that the exception captures and logs, you should not throw an identical exception back again. If the exception is thrown again, the exception must be processed at the top and the log will be logged, so repeat. If there are no special reasons, exceptions should not be caught here.
3.4 System.out Way of logging
The above log form is very arbitrary, only suitable for temporary code debugging, not allowed to submit to the formal code base.
for the temporary debug log, it is recommended to add some special sequential characters to the log output information, or you can use your own name, code, so that after debugging, before submitting the code, easy to find all the temporary code, and delete. 3.5 Log information is not clear
"Add Task Error ..." above. "There is no record of the task ID, no task name, after software deployment found an error, according to the log records can not confirm which task error, to further analyze the cause of difficulties."
Another problem in the second red circle is that you use parameters;
There are some other common mistakes that you don't have to say much.
3.6 Forget the log output is multi-threaded public
If there is another thread that is outputting the log, the above record will be interrupted, and the final display output will be inconsistent with the expected one. The right thing to do is to put this information on one line and consider using "\ r" If you need to wrap it, and consider adding if (logger.isdebugenabled ()) to judge if there is more content. The output in the second example has a system.out habit, and the relevant content should be done in one line.
3.7 Processing of multiple parameters
For the log output of multiple parameters, you can consider:
Public void Debug (String format, Object ... arguments);
However, when you use multiple parameters, you create an array of objects, and there is a certain amount of consumption, so that in performance-sensitive scenarios, you can increase the log-level judgment.