log4j 程序中打印日志

在程序中打印日志,不仅便于自已测试,还便于联调,增强代码的可读性。
不论使用common-logger, 是log4j, 还是其它的日志工具类,都会定义日志级别:DEBUG,INFO,WARN,ERROR等。

我在写程序时,就不怎么爱写这类日志,程序在编码阶段,自个能看懂,过了一段时间,
要联调,或者查找sit的测试问题,就不得不查看源代码,才能清楚调用逻辑。如果写了这类日志
就能知道在哪一步报错,快速定位问题,避免浪费时间,以后维护人员也能更好的了解
业务逻辑,便于维护。

日志可以打印在控制台: console
日志也可以打印在文件中:

log4j.rootLogger=DEBUG,stdout
DEBUG模式时,会打印第三方jar包的log.debug("xx") 日志
打印sql以及参数,如下所示:
2015-09-19 21:09:58,747 DEBUG cn.mapper.UserMapper.selectById - ==>  Preparing: select USERID, USERNAME, BIRTHDAY, SALARY from user where USERID = ?
2015-09-19 21:09:58,747 DEBUG cn.mapper.UserMapper.selectById - ==> Parameters: 200(String)

在if条件判断里面,加上日志,便于知道有没有执行里面的代码
打印返回值

在开发阶段,使用debug模式,上线时改成error模式

OFF,FATAL,ERROR,WARN,INFO,DEBUG,ALL

在开源软件中,日志应用如下:
private boolean process(Map<String, Object> map, MatchCallback callback) {
  Properties properties = new Properties();
  properties.putAll(getFlattenedMap(map));

  if (this.documentMatchers.isEmpty()) {
   if (this.logger.isDebugEnabled()) {
    this.logger.debug("Merging document (no matchers set)" + map);
   }
   callback.process(properties, map);
   return true;
  }

扫描二维码关注公众号,回复: 762308 查看本文章

  MatchStatus result = MatchStatus.ABSTAIN;
  for (DocumentMatcher matcher : this.documentMatchers) {
   MatchStatus match = matcher.matches(properties);
   result = MatchStatus.getMostSpecific(match, result);
   if (match == MatchStatus.FOUND) {
    if (this.logger.isDebugEnabled()) {
     this.logger.debug("Matched document with document matcher: " + properties);
    }
    callback.process(properties, map);
    return true;
   }
  }

  if (result == MatchStatus.ABSTAIN && this.matchDefault) {
   if (this.logger.isDebugEnabled()) {
    this.logger.debug("Matched document with default matcher: " + map);
   }
   callback.process(properties, map);
   return true;
  }

  this.logger.debug("Unmatched document");
  return false;
 }
 

猜你喜欢

转载自zw7534313.iteye.com/blog/2244796
今日推荐