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(" failed to get user info from [{}] ",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 current request:

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

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 query base "); 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. The debug (" start getting employees [{}] [{}] "year basic salary, the employee, year); Logger. The debug (" get employees [{}] [{}] years of basic salary for [{}] ", the employee, year, basicSalary); Logger. The debug (" start getting employees [{}] [{}] on [] {} "about vacations, employee, year, month); Logger. The debug (" employees [{}] [{}] [{}] month annual leave/sick leave/personal leave for [{}] / [{}] / [] {} ", the employee, year, month, annualLeaveDays, sickLeaveDays, noPayLeaveDays) ; Logger. The debug (" start count employees [{}] [{}] on [{}] deserve compensation ", the employee, year, month); Logger. The debug (" employees [{}] [{}] on [{}] deserve compensation for [{}] ", the 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(); Args [mobile=[{}],user=[{}]]", mobile, logobjects.tostring (user); } try { user.setCreateTime(new Date()); user.setUpdateTime(new Date()); userRepository.insertSelective(user); 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); Relationship =[{}]", logobjects.tostring (relationship)); if(relationship) {log.debug(" Relationship =[{}]", logobjects.tostring (relationship)); } the info (" create user and bind the mobile phone number. UserId = ({}), openId = ({}), mobile = ({}) ", the user. The getId (), the user. The getOpenId (), mobile). // If security is concerned, }catch(DuplicateKeyException e){log.info(" failed to create user and bind phone number, same user already exists. openId=[{}],mobile=[{}]",user.getOpenId(),mobile); Throw new CreateConflictException(" Create user conflict, openId =[%s]", user.getopenId ()); }}Copy the code

If there is a wrong place to write welcome comments pointed out, like Java articles, want to get Java learning materials concerned public number: program zero world can be obtained