Hi, I’m Jack

Log printing is often overlooked on a time-critical project, and you’ll probably find that the projects we encounter don’t have much of a loose cycle. And the functionality can actually be implemented with or without logging, saving a lot of time and, as is the nature of unit testing, potentially extending project time

However, as the so-called, slow is fast, think about it, our maintenance time is often two or three times more than the project cycle, and what is the nature of the maintenance object? It is the code we have written. If the code lacks the necessary log printing, or the log printing is too many and too frequent, it is not only difficult to locate the problem, but also the problem of disk storage overflow

So, when do you need to print a log?

First, when do I need to print logs?

In brief, it can be divided into the following scenarios:

  • Code debugging

  • Problem orientation

  • User behavior logs (Recording operation logs)

  • Returning for analysis

For log printing, we have a few basic specification requirements:

Two, the basic requirements of log printing specification

  • The running of the program can be recorded and monitored
  • If necessary, the internal running state of the program can be understood in detail
  • Minimize the impact on system performance (print mode in code, print log quantity and log storage, etc.)

Three, in which scenarios need to hit the log?

  • System initialization process

  • The programming language prompts an exception

  • Business process expectations are not aligned

  • System core roles, key actions of components

  • As a service provider (print input and output)

  • As a service provider (print entry)

  • Records the running of scheduled tasks

4. Log level

Commonly used are divided into the following types:

1, the ERROR

An exception that affects the normal operation of the program or the current request. Such as:

1) Failed to open the configuration file

2) All third-party connection exceptions (including error codes returned by third parties)

3) All exceptions affecting function use, including SQLException, null pointer exception and all exceptions except business exception

2, WARN

Alarm logs. Exceptions s that should not occur but do not affect the normal operation of the program or the current request.

However, once they occur, they need to be noticed. Therefore, when logs of this level reach a certain threshold, they should be notified to users or others who need to be noticed. Such as:

1) Error situations when there is a fault tolerance mechanism

2) The configuration file cannot be found, but the system can create the configuration file automatically

3) When the threshold is approaching, if the CPU memory exceeds 80% of the threshold, LOGS of WARN level must be printed

3, the INFO

Record input and output, key program nodes and other necessary information. Normally, you do not need to pay attention to it, but you can diagnose problems according to the INFO logs

1) Changes to system/business state in the Service method

2) Call parameters and call results when calling a third party (incoming and outgoing parameters)

3) The provider needs to record the input

4) Start and end execution of scheduled tasks

4, the DEBUG

Debug information: accurately records the running status of each step of the system.

5, the TRACE

Extremely detailed service invocation process node information. Do not use it in business code unless it involves calls to multi-level services (use DEBUG level instead unless specifically intended)

According to relevant materials and my experience in the project, I sorted out 15 important log printing specifications

5. Log printing specification

1. Parameter logs need to be printed for adding, deleting and modifying operations (in order to locate some abnormal service problems);

2, conditional branches need to print logs, including conditional values and important parameters;

3. Specify the log printing level and contained information

1) For provider services, it is recommended to record the input parameter at the INFO level, and the output parameter is optional

2) Consume queue messages, be sure to print message content

3) Caller service, it is recommended to record incoming and outgoing parameters at the INFO level

4) Operating environment problems, such as network errors, WARN level is recommended to record the error stack

5) For scheduled tasks, be sure to print the start time and end time of the task. For tasks involving scanning data, be sure to print the scan range

4. The exception information should include two types of information: the scene information and the exception stack information. If no, throw upward through the keyword throws/throw, which is processed by the parent method

5. Log discreetly

1) Debug logs cannot be generated in the production environment

2) Selectively output info logs

3) If you use WARN to record the business behavior information when you go online, pay attention to the problem of log output to avoid overloading server disks, and remember to delete these observation logs in time

6. The WARN log level can be used to record user input parameter errors to avoid user complaints

Pay attention to the log output level. The error level records only important errors such as system logic errors and exceptions. Do not type the error level in this scenario unless necessary. (The difference between ERROR and WARN level logs has been illustrated above)

7. Conditional output or placeholders must be used to output trace/debug/ INFO logs

Description:

logger.debug("Processing trade with id: " + id + " symbol: " + symbol);
Copy the code

For the above code, if the log level is WARN, the log will not be printed, but string concatenation will be performed, and if symbol is an object, the toString() method will be executed, wasting system resources by doing the above, but the log will not be printed

Example :(condition)

if (logger.isDebugEnabled()) {
    logger.debug("Processing trade with id: " + id + " symbol: " + symbol);
}

Copy the code

Example :(placeholder)

logger.debug("Processing trade with id: {} symbol : {} ", id, symbol);
Copy the code

8. It is not allowed to log and then throw an exception, because this will log multiple times, only one log is allowed

Example:

If (virtualIpPortCrash) {log.error(" Access virtual IP port conflict "); Throw new BusinessException(" Access virtual IP port conflict "); }Copy the code

9. Do not allow System print statements (including System.out.println and system.error. Println) to print logs

Do not allow e.printStackTrace

11. Log performance considerations. If the code is core code and the execution frequency is very high, it is recommended to add judgment to the output log, especially the low-level output

12. [Mandatory] Applications should not directly use the API of logging system (Log4j, Logback), but should rely on the API of logging framework SLF4J, using the facade mode of logging framework, which is conducive to maintenance and the unification of log processing mode of each class

import lombok.extern.slf4j.Slf4j; //1- Slf4j //2- Directly print logs using log.info() (error, WARN, trace and DEBUG levels are also supported) log.info("service update success:{}................" ,serviceEntity.getName());Copy the code

13. [Mandatory] It is recommended that log files be saved for at least 15 days, because some exceptions occur with “weekly” frequency

14. [Mandatory] The extension logs (such as log registration, temporary monitoring, and access logs) in the application are named appname_logtype_logname.log

LogType: indicates the logType. The recommended types are stats, desc, monitor, and visit

LogName: log description. The advantage of this naming is that the file name indicates the application, type, and purpose of the log file, and it also facilitates categorization and lookup. For example, mPPServer monitors a time zone conversion exception, for example, mppServer_Monitor_timezoneconvert.log

15. [Force] Do not print logs repeatedly, which wastes disk space. Be sure to set additivity=false in log4j.xml

Six, summarized

Well, because log printing is really important, so Jay has recently searched for a lot of relevant information, and based on his own project experience, here are 15 important log printing rules to share with you ~

Note the difference between error and WARN logs. Error logs indicate that the program fails to perform services due to errors. Warn, on the other hand, indicates log information that does not affect the normal running of the program, but requires appropriate attention.

Slow is fast, and properly printing logs in the code will get twice the result with half the effort. Otherwise, it will not only affect the quality of maintenance, but also may cause some unexpected problems

Therefore, everyone in the usual development, in order to the long-term development of the project, we must pay attention to the log oh ~

Well, that’s it. Learn a little every day, and time will show you how strong you are

Welcome to pay attention to the public account, together with continuous learning ~