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 in Java code

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "how to log in Java code". In daily operation, I believe many people have doubts about how to log in Java code. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to log in Java code". Next, please follow the editor to study!

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 you 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

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.

Using ERROR at different levels: basic concepts

Exceptions that 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)

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);} basic concepts of WARN

An exception that should not occur but does not affect the normal operation of the program and the current request:

Error conditions that occur when there is a fault-tolerant mechanism

The configuration file could not be found, but the system can create the profile 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

Changes to system / business state in the Service method

Step by step in main logic

External interface part

Client request parameters (REST/WS)

Call parameters and results when a third party is called

Description

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);}

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).

For the provided interface (REST/WS) of the whole system, use info to record the input parameters

If all service is SOA architecture, then it can be regarded as an external interface provider, then the input parameters must be recorded.

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)

Basic concepts of DEBUG

You can fill in all the relevant information you want (but it doesn't mean you can write it casually. Debug information should be meaningful, preferably with relevant parameters).

Production environment needs to turn off DEBUG information

If you need to open DEBUG in the production situation, you need to use the switch for management, can not 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); basic concepts of TRACE

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

The specification example shows @ Override@Transactionalpublic 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, the study on" how to log in Java code "is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report