Why do we declare Loggers static final?

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

    • private - so that no other class can hijack your logger
    • static - so there is only one logger instance per class, also avoiding attempts to serialize loggers
    • final - no need to change the logger over the lifetime of the class

    Also, I prefer name log to be as simple as possible, yet descriptive.

    EDIT: However there is an interesting exception to these rules:

    protected final Logger log = LoggerFactory.getLogger(getClass());
    

    as opposed to:

    private static final Logger log = LoggerFactory.getLogger(Foo.class);
    

    The former way allows you to use the same logger name (name of the actual class) in all classes throughout the inheritance hierarchy. So if Bar extends Foo, both will log to Bar logger. Some find it more intuitive.

提交回复
热议问题