Don't type the log in Java code, this is the correct log printing posture!

Yunqi information:[ Click to see more industry information]
Here you can find the first-hand cloud information of different industries. What are you waiting for? Come on!

Using slf4j

1. The use of the facade mode log framework is conducive to the maintenance and unification of the log processing methods of various classes
2. Unified implementation: Logback framework

The right way to log

When should I log

  • When you encounter a problem, you can only determine the problem through the debug function. You should consider logging. A good system can determine the problem through logging.
  • When you come across if For branches such as else or switch, a log should be printed at the first line of the branch to determine which branch has been entered
  • Often develop with function as the core. You should make sure that you can see the whole process through the log before you submit the code

Basic format

Parameterized information must be used:

logger.debug("Processing trade with id:[{}] and symbol : [{}] ", id, symbol);

For the debug log, you must judge whether it is at the debug level before using it:

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

Do not do String splicing, which will produce a lot of String objects, occupy space and affect performance.
Counter example (do not do this):

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

Use [] for parameter variable isolation

If there are parameter variables, they should be written as follows:

logger.debug("Processing trade with id:[{}] and symbol : [{}] ", id, symbol);

This format is more readable and helpful for troubleshooting.

Different levels of use


Basic concepts

Abnormal conditions that affect the normal operation of the program and the normal operation of the current request:

1. Failed to open configuration file
2. All third-party docking exceptions (including error codes returned by the third party)
3. All exceptions affecting the use of functions, including SQLException and all exceptions except business exceptions (RuntimeException and Exception)

What should not happen:

For example, if you want to use Azure to send pictures, but Azure does not respond

If there is Throwable information, you need to record the completed stack information:

log.error("Get users[{}]Error in user information for",userName,e);

Note: if an exception is thrown, please do not record the error log, which will be handled by the final processor. WeChat official account: Internet architects, in the background reply: 2T, can get my collated tutorial, all dry cargo.

Counter example (do not do this):

}catch(Exception ex){
  String errorMessage=String.format("Error while reading information of user [%s]",userName);
  throw new UserServiceException(errorMessage,ex);


Basic concepts

Exceptions that should not occur but do not affect the normal operation of the program and the current request:

1. Error conditions when there is fault tolerance mechanism
2. The configuration file cannot be found, but the system can create it automatically

Near the threshold, for example, when the cache pool occupation reaches the warning line

Records of business exceptions, such as when the interface throws a business exception, this exception should be recorded


Basic concepts

System operation information

Change of system / business status in Service method
Steps in main logic

External interface part

Client request parameters (REST/WS)
Call parameters and results when calling a third party


1. Not all services record the entry and exit points. A single and simple service is meaningless (except for job s, which need to record the start and end).
Counter example (do not do this):

public List listByBaseType(Integer baseTypeId) {"Start base query");
    BaseExample ex=new BaseExample();
    BaseExample.Criteria ctr = ex.createCriteria();
    Optionals.doIfPresent(baseTypeId, ctr::andBaseTypeIdEqualTo);"End of Query Base");
    return baseRepository.selectByExample(ex);

2. For complex business logic, it is necessary to log and record, such as e-commerce system
The order placement logic in, and the OrderAction action action (business state change). WeChat official account: Internet architects, in the background reply: 2T, can get my collated tutorial, all dry cargo.
3. For the interface provided by the whole system (REST/WS), use info to record the input parameters
4. If all service s are SOA architecture, they can be regarded as an external interface provider, and the input parameters must be recorded.
5. When invoking other third-party services, all the input and output parameters must be recorded (because it is difficult for you to trace the problems of the third-party module)


Basic concepts
1. You can fill in all the relevant information you want to know (but it doesn't mean you can write it casually. debug information should be meaningful, and it's better to have relevant parameters)
2. The production environment needs to shut down the DEBUG information
3. If DEBUG needs to be turned on in production, it needs to be managed by using the switch and cannot be turned on all the time.


If the following code appears in the code, it can be optimized:

//1. Get user's basic salary

//2. Get user leave

//3. Calculate user's salary

Optimized code:

logger.debug("Start getting employees[{}] [{}]Annual basic salary",employee,year);

logger.debug("Get employees[{}] [{}]The basic salary for the year is[{}]",employee,year,basicSalary);
logger.debug("Start getting employees[{}] [{}]year[{}]Monthly leave",employee,year,month);

logger.debug("staff[{}][{}]year[{}]Monthly annual leave/sick leave/Personal leave is[{}]/[{}]/[{}]",employee,year,month,annualLeaveDays,sickLeaveDays,noPayLeaveDays);
logger.debug("Start counting employees[{}][{}]year[{}]Monthly salary due",employee,year,month);

logger.debug("staff[{}] [{}]year[{}]The monthly salary is[{}]",employee,year,month,actualSalary);


Basic concepts

In particular, the details of the system operation are completed. The information in the business code is not used. (unless there are special purposes, please use DEBUG level instead) to pay attention to WeChat official account: Internet architect, in the background reply: 2T, get my collated tutorial, all dry cargo.

Specification example

public void createUserAndBindMobile(@NotBlank String mobile, @NotNull User user) throws CreateConflictException{
    boolean debug = log.isDebugEnabled();
        log.debug("Start to create user and bind mobile number. args[mobile=[{}],user=[{}]]", mobile, LogObjects.toString(user));
    try {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
            log.debug("User information created successfully. insertedUser=[{}]",LogObjects.toString(user));
        UserMobileRelationship relationship = new UserMobileRelationship();
        relationship.setCreateTime(new Date());
        relationship.setUpdateTime(new Date());
            log.debug("Bind mobile phone successfully. relationship=[{}]",LogObjects.toString(relationship));
        }"Create user and bind mobile number. userId=[{}],openId=[{}],mobile=[{}]",user.getId(),user.getOpenId(),mobile); // If you think about safety, desensitize your phone number
    }catch(DuplicateKeyException e){"Failed to create user and bind mobile number,The same user already exists. openId=[{}],mobile=[{}]",user.getOpenId(),mobile);
        throw new CreateConflictException("Conflict creating user, openid=[%s]",user.getOpenId());

[yunqi online class] product technology experts share every day!
Course address:

Join the community immediately, face to face with experts, and keep abreast of the latest news of the course!
[yunqi online classroom community]

Original release time: June 24, 2020
Author: Sigma
This article comes from:“ Internet architect WeChat official account ”For more information, please pay attention to "[Internet architect](

Tags: Java Mobile REST

Posted on Wed, 24 Jun 2020 03:55:03 -0400 by grooveman