Use slf4j

  • The facade logging framework helps maintain and unify the log processing of each class.
  • Unified implementation: Logback framework

The correct way to log

When should I log in

  • When you encounter a problem, you can only use the debug function to determine the problem, you should consider logging, good system, is able to use the log to determine the problem.
  • When you meet if… For branches like else or switch, a log is printed on the first line of the branch to determine which branch was entered
  • Often feature centered development, you should be sure to see the flow through the log before you commit code

The basic format must use parameterized information:

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

Before using debug logs, check whether the log level is DEBUG:

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

Do not concatenate strings, as this will create a lot of strings, which will take up space and affect performance. Counterexample (don’t do this):

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

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);
Copy the code

This format is more readable and more helpful for troubleshooting problems.

Different levels of use

ERROR: An exception that affects the normal operation of the program or the current request:

  • Failed to open the configuration file. Procedure
  • All third-party connection exceptions (including error codes returned by third parties)
  • All exceptions that affect the use of functionality, including :SQLException and all exceptions except business exceptions (runtimeExceptions and Exceptions)

What should not happen: If you want to use Azure to upload images, Azure does not respond

If there is Throwable information, the completed stack information needs to be recorded:

log.error("Error getting user information for user [{}]",userName,e);
Copy the code

Note If an exception is thrown, do not record error logs. The final handler handles the exception:

Counterexample (don’t do this):

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

WARN Basic concepts exceptions that should not occur but do not affect the normal operation of the program or the current request: 1. Error conditions that occur when a fault tolerance mechanism is in place. 2

The cache pool usage reaches the warning line

Record service exceptions, for example: 1. When an interface throws a service exception, record the exception

INFO: Basic concept System running information 1. Changes to system or Service status in the Service method 2

External interface part 1. Client request Parameters (REST/WS) 2. Call parameters and call results when calling a third party

Note 1. Not all services record inbound and outbound entries. A single service is meaningless (except job, whose start and end are recorded). Counterexample (don’t do this):

public List listByBaseType(Integer baseTypeId) {


   log.info("Start base search.");
BaseExample ex=new BaseExample();
BaseExample.Criteria ctr = ex.createCriteria();
ctr.andIsDeleteEqualTo(IsDelete.USE.getValue());
Optionals.doIfPresent(baseTypeId, ctr::andBaseTypeIdEqualTo);
   log.info("Base query completed.");
return baseRepository.selectByExample(ex);


}
Copy the code

2. For complex business logic, logging and buried logging are required, such as order placing logic in e-commerce systems and OrderAction operations (business state changes). 4. If all services are SOA architectures, they can be considered as an external interface provider and must be logged. 5. When calling other third-party services, all outgoing and incoming parameters must be recorded (because it is difficult to trace problems with third-party modules).

Basic concepts of debugging 1. You can fill in all the information you want to know (but you can not write the information at will. The relevant parameters are recommended.) 2.

You can optimize the following codes if they exist in the code:

//1. Obtain user's basic salary //2. Obtain user's vacation status //3. Calculate the user's salaryCopy the code

Optimized code:

logger.debug("Start collecting employee [{}] [{}] annual base salary",employee,year);
logger.debug("Obtain employee's base salary for [{}] [{}] years of [{}]",employee,year,basicSalary);
logger.debug("Start obtaining employee's [{}] [{}] year [{}] [{}] monthly leave status",employee,year,month);

logger.debug("Employee [{}][{}] [{}] year [{}] monthly annual leave/sick leave/personal leave is [{}]/[{}]/[{}]",employee,year,month,annualLeaveDays,sickLeaveDays,noPayLeaveDays);
logger.debug("Start calculating employee's salary for [{}][{}] [year [{}][{}].",employee,year,month);

logger.debug("Employee [{}] [{}] year [{}] month salary due is [{}]",employee,year,month,actualSalary);
Copy the code

TRACE Basic concepts This command is used to TRACE detailed information about system running completion. Do not use this command in service code.(Use the DEBUG level instead unless you want to do so.)

Specifications Example Description

@Override
@Transactional
public void createUserAndBindMobile(@NotBlank String mobile, @NotNull User user) throws CreateConflictException{
    boolean debug = log.isDebugEnabled();
    if(debug){
        log.debug(Args [mobile=[{}],user=[{}]], mobile, LogObjects.toString(user));
    }
    try {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userRepository.insertSelective(user);
        if(debug){
            log.debug(InsertedUser =[{}]",LogObjects.toString(user));
        }
        UserMobileRelationship relationship = new UserMobileRelationship();
        relationship.setMobile(mobile);
        relationship.setOpenId(user.getOpenId());
        relationship.setCreateTime(new Date());
        relationship.setUpdateTime(new Date());
        userMobileRelationshipRepository.insertOnDuplicateKey(relationship);
        if(debug){
            log.debug("Relationship =[{}]",LogObjects.toString(relationship));
        }
        log.info(UserId =[{}],openId=[{}],mobile=[{}]",user.getId(),user.getOpenId(),mobile); }catch(DuplicateKeyException e){log.info(OpenId =[{}],mobile=[{}]" openId=[{}],mobile=[{}]",user.getOpenId(),mobile);
        throw new CreateConflictException("Create user conflict, openID =[%s]",user.getOpenId()); }}Copy the code

Author: Lrwin

Source: http://t.cn/E9BkD7a



Welcome to follow my wechat public account “Code farming breakthrough”, share Python, Java, big data, machine learning, artificial intelligence and other technologies, pay attention to code farming technology improvement, career breakthrough, thinking transition, 200,000 + code farming growth charge first stop, accompany you have a dream to grow together