In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
The main content of this article is to explain "what is the correct way to log in Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what is the correct way to log in Java"?
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 often developed with functionality as the core. You should make sure that the whole process can be seen through the log before submitting the code.
Basic format
You 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 [] to isolate parameter variables
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 concept
Exceptions that affect the normal operation of the program and the normal operation of the current request:
Failure to open configuration file all third-party docking exceptions (including error codes returned by third parties) all exceptions that affect the use of features, including: SQLException and all exceptions except business exceptions (RuntimeException and Exception)
Something that should not have happened:
For example, you want to use Azure to send pictures, but Azure does not respond.
If you have Throwable information, you need to record the completed stack information:
Log.error ("error getting user information for user [{}]", userName,e)
Description
If an exception is thrown, do not record the error log, and the final handler 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);}
WARN
Basic concept
An exception that should not occur but does not affect the normal operation of the program and the current request:
When there is a fault-tolerant mechanism, the configuration file can not be found, but the system can create the configuration file automatically.
When it is approaching the critical value, for example:
Cache pool occupancy reaches warning line
Records of business exceptions, such as:
When an interface throws a business exception, this exception should be logged
INFO:
Basic concept
System operation information
The steps in the main logic of changing the system / business state in the Service method
External interface part
Client request parameters (REST/WS) call parameters and results when a third party is called
Description
1. Not all service records entrances and exits, and a single, simple service is meaningless (except for job, where job needs to record the start 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 ("query base end"); return baseRepository.selectByExample (ex);}
two。 For complex business logic, log management and buried records are needed, such as order placing logic in e-commerce system, and OrderAction operation (business state change).
3. For the provided interface (REST/WS) of the whole system, use info to record the input parameters
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 problems with third-party modules)
DEBUG
Basic concept
You can fill in all the relevant information you want to know (but it doesn't mean you can write freely, debug information should be meaningful, preferably with relevant parameters) the production environment needs to turn off DEBUG information. If you need to turn on DEBUG in production, you need to use the switch to manage it, which cannot be turned on all the time.
Description
If the following code appears in the code, you can optimize it:
/ / 1. Get the user's basic salary / / 2. Get the user's vacation situation / / 3. Calculate the salary due to the user
Optimized code:
Logger.debug ("start getting employees'[{}] [{}] annual base salary", employee,year); logger.debug ("get employees'[{}] [{}] annual base salary is [{}]", employee,year,basicSalary); logger.debug ("start getting employees'[{}] [{}] annual [{}] 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 [{}] monthly salary", employee,year,month) Logger.debug ("employee [{}] [{}] monthly salary is [{}]", employee,year,month,actualSalary)
TRACE
Basic concept
Very 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 binding mobile phone 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 phone successfully. Relationship= [{}] ", LogObjects.toString (relationship);} log.info (" create a user and bind a mobile phone number. UserId= [{}], openId= [{}], mobile= [{}] ", user.getId (), user.getOpenId (), mobile); / / if security is considered, the phone number remembers desensitization} catch (DuplicateKeyException e) {log.info (" failed to create a user and bind a mobile phone number, the same user already exists. OpenId= [{}], mobile= [{}] ", user.getOpenId (), mobile); throw new CreateConflictException (" create user conflict, openid= [% s] ", user.getOpenId ());}}
At this point, I believe you have a deeper understanding of "what is the correct way to log in Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.