Copyright belongs to the author, any form of reprint, please contact the author to obtain authorization and indicate the source.
What is a log
Simply put, a log is a record of the program’s running track, easy to find key information, but also convenient to quickly locate and solve problems.
We Java programmers rely on Eclipse/ Idea and other development tools to track and solve bugs when developing projects. In the development environment, we can do this, but the project released to test, production environment? You might say you can use remote debugging, but that’s not actually allowed.
Therefore, logging serves as a means for developers and testers to locate problems when there is no Debug tool in the test or production environment. If the logs are well typed, online problems can be quickly located and solved according to the log track. On the contrary, if the log output is poor and the fault cannot be located, the system performance will be affected.
The best projects are the ones that can locate problems based on logs, not the ones that can debug online or get frustrated when you can’t find a useful log…
Common Logging frameworks
Log4j, Logging, Commons-logging, SLF4J, logback, etc. I believe that most people do not understand their relationship, below I will introduce one by one, after you no longer silly not clear.
Logging
As you can see, this is Java’s own logging utility class, which has been available since JDK 1.5, under the java.util.logging package.
More information about Java Logging can be found in the official documentation
Log4j
Log4j is Apache’s open source logging framework and one of the most popular in the market. Most of you haven’t used Java Logging, but you can’t say you haven’t used Log4j. This has been the case since I started working on Java projects.
Note: Log4j was discontinued from maintenance by Apache on 08/05, 2015, and users need to switch to Log4j2.
Here’s the official announcement:
On August 5, 2015 the Logging Services Project Management Committee announced that Log4j 1.x had reached end of life. For complete text of the announcement please see the Apache Blog. Users of Log4j 1 are recommended to upgrade to Apache Log4j 2.
Copy the code
Log4j2 official address
commons-logging
Log4j is a concrete implementation of the logging framework, while Commons-logging is the logging facade interface. It is also the first logging facade interface provided by Apache. Users can choose a different logging implementation framework according to their preferences without changing the logging definition. Accord with face interface abstract programming.
For more details, please refer to the official instructions
Slf4j
Simple Logging Facade for Java is the same concept as Apache Commons-logging. Neither is a concrete Logging framework. You can specify other mainstream Logging implementation frameworks.
Slf4j’s official address
Slf4j is also the mainstream logging facade framework. Using Slf4j, you can use placeholders for parameters flexibly, simplify your code, and make it more readable, as we’ll see later.
Logback
Logback is the native implementation framework of Slf4j, also from Log4j alone, but has more advantages, features, and performance than Log4j, and is now used to replace Log4j in the mainstream.
Logback’s official address
Why did Logback become mainstream?
Logback is a relatively large improvement over Log4J, both in design and implementation. But while it’s hard to count them all, here are some of the reasons why you chose Logback over Log4J. Keep in mind that Logback and Log4J are conceptually similar in that they were built by the same group of developers. So if you’re already familiar with Log4j, you can get started with Logback in no time. If you like using Log4j, you may be tempted to use Logback.
Faster execution
Based on our previous work with Log4J, Logback has rewritten the internal implementation to be up to 10 times faster in certain scenarios. Logback components require less memory while keeping them faster.
See “Reasons to Migrate from Log4j to LogBack” for more information.
Summary of Log Framework
Commons-loggin, SLF4J is just a logging abstraction facade, not a concrete logging framework. Log4j and Logback are concrete logging implementation frameworks. In general, slF4J + Logback is strongly recommended. Slf4j + Log4J and Commons-logging + log4j are also available.
As you can see from the figure above, SLF4J is very powerful, not only with various logging frameworks, but also with Commons -logging.
Details about log levels
Logs are output by grade. Different Settings are used to print different logs on different occasions. The Log4j logging framework, the most commonly used, is described at the logging level, which is also quite complete. Other logging frameworks are similar.
The Log4j Level class org.apache.log4j.Level defines log levels. The log output priority ranges from highest to lowest.
The level of logging | describe |
---|---|
OFF | Off: Indicates the highest level. No log is generated. |
FATAL | Fatal: An error whose output is very serious and may cause the application to terminate. |
ERROR | Error: Output error, but the application continues to run. |
WARN | Warning: Output may be potentially hazardous. |
INFO | Information: Displays detailed information about the application running process. |
DEBUG | Debug: Output more detailed information useful for debugging applications. |
TRACE | Tracking: output more detailed program running track. |
ALL | All: Displays information about all levels. |
Therefore, log priorities are in the following order:
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
If log is set to L, an output log of level P will be output only when P >= L.
That is, if the log level L is set to INFO, subsequent logs are output only when the output level of P is SET to INFO and WARN.
For the specific output relationship, please refer to the following figure:
Now that you know the logging level, and this is just the basics, how do you know the logging specification and how to correctly log posture? !
Rules for logging
It has been said at the beginning that the log can not be randomly hit, otherwise it will not play the role that the log should play, but also cause the burden of the system. Some large companies such as BAT and Huawei have requirements on log specification, and have specifications on what log should be typed and when.
Ali’s Java Development Manual, released last year, has a chapter on logging specifications, so let’s review what’s there.
The following is ali’s Java Development Manual ultimate edition log protocol.
There are many specifications, here will not detail one by one, the complete ultimate version can be obtained in the wechat public number “Java Technology Stack “reply” manual “. Here I just want to tell you that there are strict norms in large companies to play log, not you just play.
Ali is a first-line Internet company, the log specifications developed are also in line with our requirements, very reference significance, can be popularized this log ali protocol is really very good.
How to log correctly in a project?
-
Private static final Logger LOG = loggerFactory.getLogger (this.getClass()); There is usually only one LOG object per class. If there is a parent class, you can define LOG in the parent class. The log variable type is defined as a facade interface (such as Logger of SLF4J). The implementation class can be Log4j, Logback and other log implementation frameworks. Do not define the implementation class as a variable type.
-
Log.debug (“Save order with order no: [{}], and order amount: [{}]”); This readability makes it easy to see that [] contains the output dynamic parameters, {} is used as a placeholder like a binding variable, and only handles the parameters when it is actually ready to print, making it easier to locate problems. If the log framework does not support parameterization and the log level is not supported during log output, redundant objects will be created and memory will be wasted. In this case, you need to use isXXEnabled. For example:
if(log.isdebugenabled ()){// String concatenation is useless code concatenation if the LOG is not parameterized and debug is not enabled. Logger.debug ()"Save order with order no:" + orderNo + ", and order amount:" + orderAmount); } Copy the code
At least the debug level must be enabled. The online log level must be at least info. It is recommended to use SLF4J’s facade interface, which can output logs in parameterized form, and the debug level does not need to be determined by if, simplifying the code.
-
Output logs of different levels. The most commonly used log levels are ERROR, WARN, INFO, and DEBUG. What are the application scenarios of these four levels?
An ERROR is typically used to record any exception ERROR message (Throwable) that occurs in a program, or to record business logic errors. WARN is used to record errors in user input parameters. INFO is the lowest and default log level. It is used to record useful information during program running. Such as the start and end of the program running, time, important parameters and other information, need to pay attention to the selective and meaningful output, when the time to find their own problems to look at a pile of logs but can not find the key log is meaningless. The DEBUG level is used to record intermediate parameters during operation. It can be enabled only in the development environment, but optionally in the test environment.
Several wrong logging methods
-
Do not use system.out.print.. You can only output logs using the log framework, not using System.out.print.. This will only be printed to the Tomcat console and will not be recorded in a log file, which makes it difficult to manage the log. If the log is discarded by starting as a service, the log will not be found.
-
Don’t use e.printStackTrace() first look at its source:
public void printStackTrace() { printStackTrace(System.err); } Copy the code
It also outputs to the Tomcat console using system. err.
-
Do not output logs after an exception is thrown. For example, if a custom service exception is thrown after an exception is caught, you do not need to record error logs. The final catcher handles the exception. Do not throw exceptions and print error logs at the same time. Otherwise, log output will be repeated.
try { // ... } catch (Exception e) {// error log.error ("xxx", e); throw new RuntimeException(); } Copy the code
-
Do not use the concrete logging implementation class InterfaceImpl interface = new InterfaceImpl(); Does this code make sense to everyone? It is also a principle of the software design pattern that you should program for objects that are interfaces, not implementations.
Interface interface = new InterfaceImpl(); The same is true in the logging framework. As mentioned above, the logging has a facade interface and an implementation framework, so don’t program for implementation.
-
Not all error information is displayed. The following code does not record detailed stack exception information. Only the basic description of the error is recorded.
try { // ... } catch (Exception e) {// error log.error ('XX has an exception ', e.getMessage()); / / correct the error ('XX has an exception ', e); } Copy the code
-
Do not use the wrong log level ever to locate a problem online, my colleague confidently said to me: obviously output the log ah, why can’t find… “And then I looked at his code and it looked like this:
try { // ... } catch (Exception e) {// error log.info ("XX has an exception...", e); } Copy the code
Do you see any problems? The error log is output to the INFO log file. My colleagues desperately search in the error log file. How can they find it?
-
If your framework uses the low-performing Log4j framework, do not print logs in thousands of for loops. This can drag down your application. If your application has slow response times, consider whether you are printing too much log.
for(int i=0; i<2000; i++){ LOG.info("XX"); } Copy the code
The best way to do this is to record the bullet points in the loop and print the summary out of the loop.
-
Disable debug on an online environment this is the last and most important point. The first reason is that there are too many debug logs in the project itself, and the second reason is that various frameworks also use a large number of debug logs. If debugging is enabled online, the disk will be filled soon, affecting the normal operation of the service system.