简体   繁体   English

创建记录器时如何避免重复自己?

[英]How do you avoid repeating yourself when creating a logger?

I think the common idiom for creating instances of java.util.logging.Logger is this: 我认为创建java.util.logging.Logger实例的常用习惯是:

public class SomeClassName {

    private static final Logger LOG = Logger.getLogger(SomeClassName.class.getName());

}

My IDE will manage changing the line appropriately when I refactor my code (change the name of the class, for example). 当我重构代码时,我的IDE将管理适当的更改行(例如,更改类的名称)。 It still bugs me that I have to repeat the name of the class, though. 不过,我仍然不得不重复我的课程名称。 What I'd really like to do is something like Logger.getLogger(getName()) or Logger.getLogger(class.getName()) , but this isn't legal Java in a static initilization. 我真正想做的是像Logger.getLogger(getName())Logger.getLogger(class.getName()) ,但这不是静态启动中的合法Java。

Is there a better way of getting at a logger that doesn't involve repeating myself? 是否有更好的方法来获取不涉及重复自己的记录器?

Issue 137 of The Java Specialists' Newsletter deals with this problem. Java专家通讯的第137期处理此问题。 It recommends applying a logger factory, which can detect the actual class name eg by generating an exception and analysing the call stack. 它建议应用一个记录器工厂,它可以检测实际的类名,例如通过生成异常并分析调用堆栈。

I personally find this worse than the original problem, but this is just my 2 cents. 我个人认为这比原来的问题更糟糕,但这只是我的2美分。 At any rate, technically it is interesting, so here it is: 无论如何,技术上它很有趣,所以这里是:

public class LoggerFactory {
  public static Logger make() {
    Throwable t = new Throwable();
    StackTraceElement directCaller = t.getStackTrace()[1];
    return Logger.getLogger(directCaller.getClassName());
  }
}

...

public class BetterApplication {
  private final static Logger logger = LoggerFactory.make();

  ...
}

I create an Eclipse code template and use it each time. 我创建了一个Eclipse代码模板并且每次都使用它。

在此输入图像描述

You just have to type logger and press Ctrl + Space to activate it. 您只需键入logger并按Ctrl + Space即可激活它。

我们这样做:

private Logger log = Logger.getLogger(this.getClass());

I use a plugin called log4e which is handy for logging. 我使用一个名为log4e的插件,它可以方便地进行日志记录。

http://log4e.jayefem.de/ http://log4e.jayefem.de/

You can use it to automatically add before/after logging for a method or a whole class. 您可以使用它在记录方法或整个类之前/之后自动添加。
Also you can get it to auto replace System.out.println's with logger statements. 您还可以使用logger语句自动替换System.out.println。
Very handy. 非常便利。

There is a trick to get the name of current class from a static context, I can't cite it from memory but it involved throwing an exception inside the static block and reading stack trace to get to the name of the class. 有一个技巧可以从static上下文中获取当前类的名称,我不能从内存中引用它,但它涉及在静态块中抛出异常并读取堆栈跟踪以获取类的名称。 However, it's quite a hack, so in practice I find repeating myself better than playing such tricks. 然而,这是一个非常黑客,所以在实践中我发现重复自己比玩这样的技巧更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM