Why do we declare Loggers static final?

后端 未结 14 1905
陌清茗
陌清茗 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 02:01

    According the the info I read from the internet about making the logger static or not, the best practice is to use it according to the use cases.

    There are two main arguments:

    1) When you make it static, it is not garbage collected (memory usage & performance).

    2) When you don't make it static it is created for each class instance (memory usage)

    Thus, When you are creating a logger for a singleton, you don't need to make it static. Because there will be only one instance thus one logger.

    On the other hand, if you are creating a logger for a model or entity class, you should make it static not to create duplicated loggers.

    0 讨论(0)
  • 2020-11-28 02:03

    This code is vulnerable,but, after Java7, we can use Logger lgr = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); instead of static logger.

    0 讨论(0)
提交回复
热议问题