Home > Java > javaTutorial > How to use Java logging correctly

How to use Java logging correctly

little bottle
Release: 2019-04-28 16:55:49
forward
2604 people have browsed it

Regarding logs, everyone thinks it is relatively simple. We only need to introduce the relevant dependency packages, and the rest is to "enjoy" printing the information we need in the project. But often the simpler things are, the easier it is for us to ignore them, leading to some undesirable bugs. As a rigorous programmer, how can we let this happen? So let’s learn about the correct usage postures about logs.

Text

Log specifications

Naming

The first is the naming of the log file. Try to be familiar with the name and understand it within the team. A unified naming convention must be used, otherwise "dirty, messy" log files will affect everyone's efficiency in troubleshooting problems. It is recommended to name it "projectName_logName_logType.log", so that through the name, you can clearly know which project the log file belongs to, what type it is, and what function it has. For example, in our MessageServer project, the log file name related to monitoring Rabbitmq consumers can be defined as "messageserver_rabbitmqconsumer_monitor.log".

Save time

Regarding the log storage time, it is recommended to keep ordinary log files for 15 days. If it is more important, it can be extended according to the actual situation. For details, please refer to the respective server disk space and log file size. Make the best choice.

Log levels

Common log levels are as follows:

DEBUG level: records debugger-related information. INFO level: records meaningful information about the normal operation of the program. WARN level: records information that may potentially cause errors. ERROR level: records information about the current program error and needs attention and processing. Fatal level: Indicates that a serious error has occurred and the program will interrupt execution.

It is recommended to use these four levels in the project, ERROR, WARN, INFO, and DEBUG.

Correct posture

1. Judge the log level in advance

//条件判断if(logger.isDebugEnabled){
    logger.debug("server info , id : " + id + ", user : " + user);
}//使用占位符logger.debug("server info , id : {}, user : {}",id,user);
Copy after login

DEBUG and INFO level logs exist relatively frequently in our program. When our project becomes larger and the number of logs increases, in order to run the program more efficiently, we must judge based on conditions or placeholder to print the log. why? If the log level configured in our project is WARN, then for our following log output statement 'logger.debug("server info, id: "id", user: "user);', although the log will not be printed, However, the string splicing operation will be performed. Here our user is an instance object, so the toString method will also be executed, which wastes a lot of system resources.

2. Avoid redundant log output

In our production environment, the output of DEBUG logs is generally prohibited. The frequency of printing is very high, which can easily cause serious damage to normal running programs. Impact, we have encountered similar situations in our recent projects.

Then it’s time to learn to use the additivity attribute

<logger name="xx" additivity="true">
Copy after login

If configured to true here, it is the default situation. At this time, the current Logger will inherit the Appender of the parent Logger. To put it bluntly, it is the current In addition to being output to the current log file, the log output will also be output to the parent file. So generally, in order to avoid repeated printing, we will set this parameter to false to reduce unnecessary output.

3. Ensure that the log record information is complete

In our code, the log record content must include the exception stack. Please do not output simple logs such as "XX error" at will. This is very important for Debugging errors is not helpful. Therefore, we must bring stack information when recording exceptions, such as

logger.error("rabbitmq consumer error,cause : "+e.getMessage(),e);
Copy after login

Remember that when outputting an object instance, you must ensure that the object overrides the toString method, otherwise only its hashCode value will be output.

4. Define the logger variable as static

private static final Logger logger = LoggerFactory.getLogger(XX.class);
Copy after login

Ensure that an object only uses one Logger object to avoid re-creating it every time, otherwise it may cause OOM.

5. Use the log level correctly

try{    //..}catch(xx){
    logger.info(..);
}
Copy after login

In this way, all the information that was originally ERROR will be printed in the INFO log file, and uninformed colleagues will still stare at the error log. , and the problem cannot be found, it will affect work efficiency, right?

6. It is recommended to use the slf4j logback combination

The logback library itself has already implemented the slf4j interface, so there is no need to introduce redundant adapter, and logback also has more advantages. It is recommended that new projects can use this combination. Another thing to note is that after introducing slf4j, we should pay attention to whether the log library actually used is introduced by us, or it may use the log library brought in by our third-party dependency package, which may cause our The log is invalid.

7. Log aggregation analysis

Log aggregation can unify the logs between different servers for analysis and processing. Nowadays, ELK technology stack or EFG (fluentd elasticsearch grafana) etc. They are some relatively mature open source solutions.

Taking ELK as an example, you can directly read the log files printed by the application through logstash on our server, or you can also configure the relevant socket information in the log configuration file in our project and print it. At this time, the log information is output directly to logstash. Then it is handed over to elasticsearch for storage and kibana display.

Related tutorials: Java video tutorial

The above is the detailed content of How to use Java logging correctly. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:oschina.net
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template