首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何减少Logger.getLogger(...)每个类中的样板文件

如何减少Logger.getLogger(...)每个类中的样板文件
EN

Stack Overflow用户
提问于 2016-07-04 10:47:50
回答 3查看 341关注 0票数 4

为了在Java中使用logger,现在我使用如下代码:

代码语言:javascript
复制
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;

try {

  // This block configure the logger with handler and formatter
  fh = new FileHandler("c:\\MyLogFile.log", true);
  logger.addHandler(fh);
  logger.setLevel(Level.ALL);
  SimpleFormatter formatter = new SimpleFormatter();
  fh.setFormatter(formatter);

  // the following statement is used to log any messages   
  logger.log(Level.WARNING,"My first log");

} catch (SecurityException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

但是为每个类文件添加以下代码总是会让我有点困扰:

代码语言:javascript
复制
Logger l = Logger.getLogger("MyLog");

我该如何重构这种重复呢?

EN

回答 3

Stack Overflow用户

发布于 2016-07-04 12:40:30

登录每个类文件是一种正确的方式,尽管它看起来有点冗余。

日志记录的重要功能是记录异常。如果我们想要直接找到异常发生的位置,我们应该知道类名和方法名。

但是您可能在捕获异常时忘记了记录日志。

票数 0
EN

Stack Overflow用户

发布于 2016-07-04 22:56:23

票数 0
EN

Stack Overflow用户

发布于 2018-08-20 02:16:18

您可以使用项目lombok来完成此操作:

project lombok is here

下面是他们网页上的例子,如果它曾经不可用的话。要清楚的是,它仍然在你的结果字节码中生成语句,但它停止了bolierplate,现在你将有一个更小的语句,但在它的马的课程,但我目前工作的项目团队喜欢它。

代码语言:javascript
复制
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

@Log
public class LogExample {

  public static void main(String... args) {
    log.error("Something's wrong here");
  }
}

@Slf4j
public class LogExampleOther {

  public static void main(String... args) {
    log.error("Something else is wrong here");
  }
}

@CommonsLog(topic="CounterLog")
public class LogExampleCategory {

  public static void main(String... args) {
    log.error("Calling the 'CounterLog' with a message");
  }
}
Vanilla Java
 public class LogExample {
  private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());

  public static void main(String... args) {
    log.error("Something's wrong here");
  }
}

public class LogExampleOther {
  private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);

  public static void main(String... args) {
    log.error("Something else is wrong here");
  }
}

public class LogExampleCategory {
  private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog");

  public static void main(String... args) {
    log.error("Calling the 'CounterLog' with a message");
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38176285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档