为什么我们声明Loggers静态最终? [英] Why do we declare Loggers static final?

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

问题描述

在Java中,为什么最佳做法是声明记录器静态最终

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静态最终?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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