Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to log correctly with Java code

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to correctly use Java code to log", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to correctly use Java code to log" bar!

Use slf4j

The use of facade mode log framework is conducive to maintenance and unified log processing of each class.

Unified use of implementation: Logback framework

The correct 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 be determined through the log.

When you meet if... When a branch like else or switch prints a log on the first line of the branch, it is used to determine which branch is entered.

Development often focuses on functionality, and you should be sure that you can see the whole process through the log before you submit the code

The basic format must use parameterized information:

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

For debug logs, you must determine whether it is at the debug level before using:

If (logger.isDebugEnabled ()) {

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

}

Do not concatenate strings, which will result in a lot of String objects that take up space and affect performance. Counterexample (don't do this):

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

Use [] for parameter variable isolation. If there is a parameter variable, it should be written as follows:

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

This format is more readable and more helpful for troubleshooting.

Different levels of use

ERROR: basic concepts affect the normal operation of the program and the normal operation of the current request:

Failed to open configuration file

All exceptions of third-party docking (including error codes returned by third parties)

All exceptions that affect feature usage, including: SQLException and all exceptions except business exceptions (RuntimeException and Exception)

Things that shouldn't happen: for example, you want to use Azure to send pictures, but Azure doesn't respond.

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

Log.error ("error getting user information for user [{}]", userName,e)

Note: if an exception is thrown, do not record the error log, and the final processor will handle it:

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)

}

The basic concept of WARN should not appear but does not affect the normal operation of the program, the current request normal operation of the exception: 1, the error occurs when there is a fault-tolerant mechanism 2, the configuration file can not be found, but the system can automatically create the configuration file

When it is approaching the critical value, for example: 1. Cache pool occupancy reaches warning line.

Records of business exceptions, such as: 1. When the interface throws a business exception, it should be recorded.

INFO: basic concept system operation information 1, changes to the system / business state in the Service method 2, steps in the main logic

External interface part 1, client request parameters (REST/WS) 2, call parameters and results when a third party is called

Note 1, not all service entry and exit management records, a single, simple service is meaningless (except job, job needs to record the beginning and end,). Counterexample (don't do this):

Public List listByBaseType (Integer baseTypeId) {log.info ("start searching base")

BaseExample ex=new BaseExample ()

BaseExample.Criteria ctr = ex.createCriteria ()

Ctr.andIsDeleteEqualTo (IsDelete.USE.getValue ())

Optionals.doIfPresent (baseTypeId, ctr::andBaseTypeIdEqualTo)

Log.info ("end of search base")

Return baseRepository.selectByExample (ex);}

2. For complex business logic, log management and buried records are needed, such as order placing logic in e-commerce system, and OrderAction operation (business status change). 3. For the provided interface (REST/WS) of the whole system, use info to record input Ref 4, if all service is SOA architecture, then it can be regarded as an external interface provider, then the input parameters must be recorded. 5. When invoking other third-party services, all output and input parameters must be recorded (because it is difficult to trace the problems with the third-party module)

DEBUG basic concept 1, you can fill in all the relevant information you want to know (but it does not mean that you can write freely, debug information should be meaningful, it is best to have relevant parameters) 2, the production environment needs to turn off DEBUG information 3, if you need to turn on DEBUG in the production situation, you need to use the switch for management, which cannot be turned on all the time.

Indicates that you can optimize if the following code appears in the code:

/ / 1. Get the user's basic salary

/ / 2. Get the user's vacation information

/ / 3. Calculate the salary due to the user

Optimized code:

Logger.debug ("start getting employee [{}] [{}] annual base salary", employee,year)

Logger.debug ("get the employee's base salary for [{}] [{}]", employee,year,basicSalary)

Logger.debug ("start getting employee [{}] [{}] monthly leave", employee,year,month)

Logger.debug ("employee [{}] [{}] monthly annual leave / sick leave / personal leave is [{}] / [{}] / [{}]", employee,year,month,annualLeaveDays,sickLeaveDays,noPayLeaveDays)

Logger.debug ("start calculating employee's [{}] [{}] monthly salary", employee,year,month)

Logger.debug ("employee [{}] [{}] monthly salary is [{}]", employee,year,month,actualSalary)

TRACE basic concepts particularly detailed system operation completion information, business code, do not use. (unless there is a special purpose, use DEBUG level instead)

Specification example description

@ Override

@ Transactional

Public void createUserAndBindMobile (@ NotBlank String mobile, @ NotNull User user) throws CreateConflictException {

Boolean debug = log.isDebugEnabled ()

If (debug) {

Log.debug ("start creating users and bind mobile numbers. Args [mobile= [{}], user= [{}]]", mobile, LogObjects.toString (user))

}

Try {

User.setCreateTime (new Date ())

User.setUpdateTime (new Date ())

UserRepository.insertSelective (user)

If (debug) {

Log.debug ("user information created successfully. 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 ("bind the phone successfully. Relationship= [{}]", LogObjects.toString (relationship))

}

Log.info ("create user and bind mobile phone number. UserId= [{}], openId= [{}], mobile= [{}]", user.getId (), user.getOpenId (), mobile); / / if security is considered, the mobile phone number should be desensitized.

} catch (DuplicateKeyException e) {

Log.info ("failed to create user and bind mobile phone number, the same user already exists. OpenId= [{}], mobile= [{}]", user.getOpenId (), mobile)

Throw new CreateConflictException ("create user conflict, openid= [% s]", user.getOpenId ())

}

} Thank you for your reading, the above is the content of "how to log correctly with Java code". After the study of this article, I believe you have a deeper understanding of how to log correctly with Java code, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report