Java “self” (static) reference

非 Y 不嫁゛ 提交于 2019-12-05 03:42:47

The slightly faster

static final Logger LOG = LoggerFactory.getLogger(
       Thread.currentThread().getStackTrace()[0].getClassName());

If you do this 1000 times it will take 36 ms using Class.class.getName() and 60 ms doing it this way. Perhaps its not worth worrying about too much. ;)

You should not inherit logger. Just declare logger in each class.

But if you don't want do such useful think, just don't make it static)

I don't think there are any alternatives that are significantly different to the two in your question.

You could create a helper method like this:

public static String getCallingClassname() {
    return new RuntimeException().getStackTrace()[1].getClassName();
}

and then

static Logger LOG = LoggerFactory.getLogger(Helper.getCallingClassname());

but that's as expensive as the original version. (FWIW - 300 times as slow is probably not a major concern, unless you have thousands of these loggers. Each of these statics is initialized just once ...)

My personal preference is for the "old fashioned" way of doing it.

You don't need to use any of those. What I find convenient to use is:
//Logger

private static final Logger logger = LoggerFactory.getLogger(CreateEmployeeRecord.class or this.class);

Do it in every class that needs logging, and change class name in bracket to corresponding class wherever it's being used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!