Why do we declare Loggers static final?

后端 未结 14 2054
陌清茗
陌清茗 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:46

    Normally you initialize the logger to log using the class name -- which means that if they weren't static, you would end up with each instance of the class having an instance of it (high memory footprint), but all of these loggers would share the same configuration and behave exactly the same. That's the reason behind the static bit. Also because each Logger is initialised with the class name, to prevent conflicts with subclasses, you declare it private so it cannot be inherited. The final comes from the point that you normally don't change the Logger during the execution -- so once initialized you never "re-configured" it -- in which case it makes sense to make it final to ensure no one can change it (by mistake or otherwise). Of course if you are going to use a Logger in a different way you might need NOT to use static final -- but I would venture to guess 80% of apps would use logging as explained above.

提交回复
热议问题