Java如何打印日志

以下为《正确的打日志姿势》学习笔记。

什么时候打日志

1.程序出现问题,只能通过 debug 功能来定位问题,很大程度是日志没打好。良好的系统,通过日志就能进行问题定位。

2.if…else 或者 switch 这样的分支程序,需在分支首行打印日志,以便确定进入了哪个分支。

3.开发的功能核心,需确认可以通过日志看到整个流程。

日志基本格式

必需使用参数化信息

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

日志包含参数变量,使用方括号[]进行变量隔离

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

debug 日志,需判断为 debug 级别后,才进行使用

if (logger.isDebugEnabled()) {
    logger.debug("Processing trade width id:[{}] and symbol:[{}], id, symbol);
}

禁止进行字符串拼接,以免产生大量 String 对象,占用空间,影响性能。禁止以下做法

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

日志级别

ERROR

基本概念

影响到程序正常运行、当前请求正常运行的异常情况:

1.打开配置文件失败

2.所有第三方对接的异常(包括第三方返回错误码)

3.所有影响功能使用的异常,包括:SQLException 和除了业务异常之外的所有异常(RuntimeException 和 Exception)

不应该出现的情况:

1.比如使用 Azure 传图片,但是 Azure 未响应

如果有 Throwable 信息,需要记录完成的堆栈信息:

log.error("获取用户[{}]的用户信息时出错",userName,e);

如果进行了抛出异常操作,不要记录 error 日志,由最终处理方进行处理

//反例
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

基本概念

不影响程序、当前请求正常运行的,不应该出现的异常情况:

1.有容错机制的时候出现的错误情况

2.找不到配置文件,但是系统能自动创建配置文件

即将接近临界值的时候,例如:

  1. 缓存池占用达到警告线

业务异常的记录,比如:

1.当接口抛出业务异常时,应该记录此异常

INFO

基本概念

系统运行信息

1.Service 方法中对于系统/业务状态的变更

2.主要逻辑中的分步骤

外部接口部分

1.客户端请求参数(REST/WS)

2.调用第三方时的调用参数和调用结果

说明

1.并不是所有的 service 都进行出入口打点记录。job 需要记录开始和结束。除了 job 外,简单 service 是没有意义的。

//反例
public List listByBaseType(Integer baseTypeId) {
    log.info("开始查询基地");
    BaseExample ex=new BaseExample();
 大专栏  Java如何打印日志    BaseExample.Criteria ctr = ex.createCriteria();
    ctr.andIsDeleteEqualTo(IsDelete.USE.getValue());
    Optionals.doIfPresent(baseTypeId, ctr::andBaseTypeIdEqualTo);
    log.info("查询基地结束");
    return baseRepository.selectByExample(ex);
}

2.复杂的业务逻辑,需要进行日志打点,埋点记录,比如电商系统中的下单逻辑,以及 OrderAction 操作(业务状态变更)

3.对于整个系统提供的接口(REST/WS),使用 info 记录入参

4.如果所有的 service 为 SOA 架构,service 可以看成一个外部接口提供方,那么必需记录入参。

5.调用其他第三方服务时,需记录所有的出参和入参,以便追溯第三方模块发生的问题。

DEBUG

基本概念

1.可以填写所有想知道的相关信息,debug 信息要有意义,最好有相关参数

2.生产环境通常需要关闭 DEBUG 信息,使用开关进行管理,不能一直开启。

说明

DEBUG 日志建议进行信息整合,不要太零散:

logger.debug("开始获取员工[{}] [{}]年基本薪资",employee,year);

logger.debug("获取员工[{}] [{}]年的基本薪资为[{}]",employee,year,basicSalary);
logger.debug("开始获取员工[{}] [{}]年[{}]月休假情况",employee,year,month);

logger.debug("员工[{}][{}]年[{}]月年假/病假/事假为[{}]/[{}]/[{}]",employee,year,month,annualLeaveDays,sickLeaveDays,noPayLeaveDays);
logger.debug("开始计算员工[{}][{}]年[{}]月应得薪资",employee,year,month);

logger.debug("员工[{}] [{}]年[{}]月应得薪资为[{}]",employee,year,month,actualSalary);
TRACE

基本概念

特别详细的系统运行完成信息,业务代码中,除非有特殊用意,否则使用 DEBUG 级替代。

@Override
@Transactional
public void createUserAndBindMobile(@NotBlank String mobile, @NotNull User user) throws CreateConflictException{
    boolean debug = log.isDebugEnabled();
    if(debug){
        log.debug("开始创建用户并绑定手机号. args[mobile=[{}],user=[{}]]", mobile, LogObjects.toString(user));
    }
    try {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userRepository.insertSelective(user);
        if(debug){
            log.debug("创建用户信息成功. 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("绑定手机成功. relationship=[{}]",LogObjects.toString(relationship));
        }
        log.info("创建用户并绑定手机号. userId=[{}],openId=[{}],mobile=[{}]",user.getId(),user.getOpenId(),mobile);
    }catch(DuplicateKeyException e){
        log.info("创建用户并绑定手机号失败,已存在相同的用户. openId=[{}],mobile=[{}]",user.getOpenId(),mobile);
        throw new CreateConflictException("创建用户发生冲突, openid=[%s]",user.getOpenId());
    }
}

原文

原文地址:https://www.cnblogs.com/lijianming180/p/12361181.html