Why do we declare Loggers static final?

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

    Actually static loggers can be "harmful" as they are supposed to work in a static context. When having a dynamic environment eg. OSGi it might help to use non-static loggers. As some logging implementations do a caching of loggers internally (AFAIK at least log4j) the performance impact might negligible.

    One drawback of static loggers is eg. garbage collection (when a class is used only once eg. during initialization the logger will be still kept around).

    For more details check:

    • http://slf4j.org/faq.html#declared_static
    • https://cwiki.apache.org/confluence/display/COMMONS/Logging+StaticLog

    See also:

    • Should logger be private static or not

提交回复
热议问题