天天看点

怎么打日志

什么时候该打日志

  • 当你必须通过Debug才能定位问题的时候,说明应该打日志,好的系统,一般通过日志就能定位问题。
  • else if, switch 分支时,首行最后打印日志,以确定程序进入哪个分支。
  • 一般来说,日志可以看到整个业务流程,否则日志就是残缺的

栗子:

public void execute(String[] arguments) {
    String logInfo = "class" + this.hashCode();
    logger.info(logInfo + " start..."); //业务开始
    try { 
    /*业务逻辑实现…*/

    /*业务逻辑实现…*/
    } catch (Exception e) {
        logger.error(logInfo + " execute error", e); //业务异常结束
    }
    logger.info(logInfo + " end."); //业务正常结束
}
           

复制

  • 异常捕获是 需要打印日志,比如数据库查询,插入等操作是要打日志的,否则不知道哪个SQL出现异常了
  • 重要信息,比如说某个重要参数不能为空,此时判断是否为空,为空的记录到日志中。

栗子:

try { 
    ...
} catch (Exception e) {
   logger.error("", e);
}           

复制

打印日志方式

  • 使用正确的日志级别打印日志,只对严重的逻辑异常使用error,在程序的关键节点输出 info 日志,接口函数可打印 debug 日志,生产环境上不能使用 debug 日志,否则日志量巨大。

栗子:

对于 debug 日志级别日志,必须判断 debug 级别后才能打印日志。

if (logger.isDebugEnabled()) {
    logger.debug("Processing trade with id: " +id + " symbol: " + symbol);
}
           

复制

  • 在接口调用时,方便问题查询,可以采用 AOP 模式来打印函数接口日志
  • 线程的已经存在的无用日志,会累计大类的无用数据,可以适当提高日志级别来避免占用磁盘。