別在 Java 代碼里亂打日志了,這才是正確的日志打印姿勢(shì)!
這里是碼農(nóng)充電第一站,回復(fù)“666”,獲取一份專屬大禮包 真愛,請(qǐng)?jiān)O(shè)置“星標(biāo)”或點(diǎn)個(gè)“在看 作者:西格瑪 來源:http://lrwinx.github.io
# 使用slf4j
使用門面模式的日志框架,有利于維護(hù)和各個(gè)類的日志處理方式統(tǒng)一 實(shí)現(xiàn)方式統(tǒng)一使用: Logback框架
# 打日志的正確方式
什么時(shí)候應(yīng)該打日志
當(dāng)你遇到問題的時(shí)候,只能通過debug功能來確定問題,你應(yīng)該考慮打日志,良好的系統(tǒng),是可以通過日志進(jìn)行問題定為的。
當(dāng)你碰到if…else 或者 switch這樣的分支時(shí),要在分支的首行打印日志,用來確定進(jìn)入了哪個(gè)分支
經(jīng)常以功能為核心進(jìn)行開發(fā),你應(yīng)該在提交代碼前,可以確定通過日志可以看到整個(gè)流程
基本格式
logger.debug("Processing trade with id:[{}] and symbol : [{}] ", id, symbol);
對(duì)于debug日志,必須判斷是否為debug級(jí)別后,才進(jìn)行使用:
if (logger.isDebugEnabled()) {logger.debug("Processing trade with id: " +id + " symbol: " + symbol);}
反例(不要這么做):
logger.debug("Processing trade with id: " + id + " symbol: " + symbol);
logger.debug("Processing trade with id:[{}] and symbol : [{}] ", id, symbol);
# 不同級(jí)別的使用
ERROR:
基本概念
打開配置文件失敗 所有第三方對(duì)接的異常(包括第三方返回錯(cuò)誤碼) 所有影響功能使用的異常,包括:SQLException和除了業(yè)務(wù)異常之外的所有異常(RuntimeException和Exception)
log.error("獲取用戶[{}]的用戶信息時(shí)出錯(cuò)",userName,e);
說明:如果進(jìn)行了拋出異常操作,請(qǐng)不要記錄error日志,由最終處理方進(jìn)行處理。
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
基本概念
有容錯(cuò)機(jī)制的時(shí)候出現(xiàn)的錯(cuò)誤情況 找不到配置文件,但是系統(tǒng)能自動(dòng)創(chuàng)建配置文件
INFO:
基本概念
Service方法中對(duì)于系統(tǒng)/業(yè)務(wù)狀態(tài)的變更 主要邏輯中的分步驟
客戶端請(qǐng)求參數(shù)(REST/WS) 調(diào)用第三方時(shí)的調(diào)用參數(shù)和調(diào)用結(jié)果
說明
反例(不要這么做):
public List listByBaseType(Integer baseTypeId) {log.info("開始查詢基地");BaseExample ex=new BaseExample();BaseExample.Criteria ctr = ex.createCriteria();ctr.andIsDeleteEqualTo(IsDelete.USE.getValue());Optionals.doIfPresent(baseTypeId, ctr::andBaseTypeIdEqualTo);log.info("查詢基地結(jié)束");return baseRepository.selectByExample(ex);}
2、對(duì)于復(fù)雜的業(yè)務(wù)邏輯,需要進(jìn)行日志打點(diǎn),以及埋點(diǎn)記錄,比如電商系統(tǒng) 中的下訂單邏輯,以及OrderAction操作(業(yè)務(wù)狀態(tài)變更)。
DEBUG
基本概念
可以填寫所有的想知道的相關(guān)信息(但不代表可以隨便寫,debug信息要有意義,最好有相關(guān)參數(shù)) 生產(chǎn)環(huán)境需要關(guān)閉DEBUG信息 如果在生產(chǎn)情況下需要開啟DEBUG,需要使用開關(guān)進(jìn)行管理,不能一直開啟。
說明
//1. 獲取用戶基本薪資//2. 獲取用戶休假情況//3. 計(jì)算用戶應(yīng)得薪資
logger.debug("開始獲取員工[{}] [{}]年基本薪資",employee,year);logger.debug("獲取員工[{}] [{}]年的基本薪資為[{}]",employee,year,basicSalary);logger.debug("開始獲取員工[{}] [{}]年[{}]月休假情況",employee,year,month);logger.debug("員工[{}][{}]年[{}]月年假/病假/事假為[{}]/[{}]/[{}]",employee,year,month,annualLeaveDays,sickLeaveDays,noPayLeaveDays);logger.debug("開始計(jì)算員工[{}][{}]年[{}]月應(yīng)得薪資",employee,year,month);logger.debug("員工[{}] [{}]年[{}]月應(yīng)得薪資為[{}]",employee,year,month,actualSalary);
TRACE
基本概念
規(guī)范示例說明
public void createUserAndBindMobile( String mobile, User user) throws CreateConflictException{boolean debug = log.isDebugEnabled();if(debug){log.debug("開始創(chuàng)建用戶并綁定手機(jī)號(hào). args[mobile=[{}],user=[{}]]", mobile, LogObjects.toString(user));}try {user.setCreateTime(new Date());user.setUpdateTime(new Date());userRepository.insertSelective(user);if(debug){log.debug("創(chuàng)建用戶信息成功. 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("綁定手機(jī)成功. relationship=[{}]",LogObjects.toString(relationship));}log.info("創(chuàng)建用戶并綁定手機(jī)號(hào). userId=[{}],openId=[{}],mobile=[{}]",user.getId(),user.getOpenId(),mobile); // 如果考慮安全,手機(jī)號(hào)記得脫敏}catch(DuplicateKeyException e){log.info("創(chuàng)建用戶并綁定手機(jī)號(hào)失敗,已存在相同的用戶. openId=[{}],mobile=[{}]",user.getOpenId(),mobile);throw new CreateConflictException("創(chuàng)建用戶發(fā)生沖突, openid=[%s]",user.getOpenId());}}
- END - 最近熱文
? 程序員被公司辭退12天,前領(lǐng)導(dǎo)要求回公司講清楚代碼,結(jié)果懵了 ? 超級(jí)天才尹希:31歲成哈佛史上最年輕教授,卻因國(guó)籍引發(fā)爭(zhēng)議 ? 美團(tuán)面試題:hashCode 和對(duì)象的內(nèi)存地址有什么關(guān)系? ? 人臉識(shí)別的時(shí)候,一定要穿上衣服啊!
評(píng)論
圖片
表情

