Java logger that automatically determines caller's class name

后端 未结 21 833
礼貌的吻别
礼貌的吻别 2020-12-07 17:53
public static Logger getLogger() {
    final Throwable t = new Throwable();
    final StackTraceElement methodCaller = t.getStackTrace()[1];
    final Logger logger          


        
21条回答
  •  旧巷少年郎
    2020-12-07 18:34

    We actually have something quite similar in a LogUtils class. Yes, it's kind of icky, but the advantages are worth it as far as I'm concerned. We wanted to make sure we didn't have any overhead from it being repeatedly called though, so ours (somewhat hackily) ensures that it can ONLY be called from a static initializer context, a la:

    private static final Logger LOG = LogUtils.loggerForThisClass();
    

    It will fail if it's invoked from a normal method, or from an instance initializer (i.e. if the 'static' was left off above) to reduce the risk of performance overhead. The method is:

    public static Logger loggerForThisClass() {
        // We use the third stack element; second is this method, first is .getStackTrace()
        StackTraceElement myCaller = Thread.currentThread().getStackTrace()[2];
        Assert.equal("", myCaller.getMethodName());
        return Logger.getLogger(myCaller.getClassName());
    }
    

    Anyone who asks what advantage does this have over

    = Logger.getLogger(MyClass.class);
    

    has probably never had to deal with someone who copies and pastes that line from somewhere else and forgets to change the class name, leaving you dealing with a class which sends all its stuff to another logger.

提交回复
热议问题