为什么我们将 Loggers 声明为 static final? [英] Why do we declare Loggers static final?

查看:28
本文介绍了为什么我们将 Loggers 声明为 static final?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,为什么最好的做法是声明一个记录器 static final?

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

private static final Logger S_LOGGER

推荐答案

  • private - 这样其他类就不能劫持你的记录器
  • static - 所以每个类只有一个记录器实例,也避免尝试序列化记录器
  • final - 无需在类的整个生命周期内更改记录器
    • 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
    • 此外,我更喜欢名称 log 尽可能简单但具有描述性.

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

      但是这些规则有一个有趣的例外:

      However there is an interesting exception to these rules:

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

      相反:

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

      前一种方式允许您在整个继承层次结构中的所有类中使用相同的记录器名称(实际类的名称).因此,如果 Bar 扩展 Foo,两者都会记录到 Bar 记录器.有些人觉得它更直观.

      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.

      这篇关于为什么我们将 Loggers 声明为 static final?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆