Why do we declare Loggers static final?

后端 未结 14 2031
陌清茗
陌清茗 2020-11-28 01:19

In Java, why is it best practice to declare a logger static final?

private static final Logger S_LOGGER
14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 01:41

    To answer that question, you should have asked yourself what "static" and "final" are for.

    For a Logger, (I assume you talk about Log4J Logger class) you want a category per class. Which should lead to the fact that you assign it only once, and there is no need for more than one instance per class. And presumably there is no reason to expose the Logger object of one class to another, so why dont make it private and follow some OO-Principles.

    Also you should note, that the compiler is able to take benefits of that. So your code performs a bit better :)

提交回复
热议问题