java 记录器应该总是最终的和静态的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7324386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:32:28  来源:igfitidea点击:

Should be logger always final and static?

javaloggingstaticfinal

提问by user710818

Class can be accessed from many threads. Must be logger in this case also be final and static? Thanks.

可以从多个线程访问类。在这种情况下必须是记录器也必须是最终的和静态的?谢谢。

回答by ataylor

All major java logging packages (java.util.logging, log4j, etc.) are synchronized and thread safe. The standard pattern of a private final staticlogger per class is fine even if the class is called from multiple threads.

所有主要的 Java 日志包(java.util.logginglog4j等)都是同步的和线程安全的。private final static即使从多个线程调用该类,每个类的记录器的标准模式也很好。

回答by uncaught_exceptions

Yes the logger should be static and final. Also preferably private. There needs be only one logger instance per class and also unless you are going to change the log preference dynamically, it is better to make it final.

是的,记录器应该是静态的和最终的。也最好是私人的。每个类只需要一个记录器实例,并且除非您要动态更改日志首选项,否则最好将其设为最终。

Logger are thread safe and you do not have to worry about threading.

Logger 是线程安全的,您不必担心线程问题。

回答by John B

Making the logger final and or static will not in any way affect the thread-safety of the use of the logger. If the logger instance is being used from multiple threads than ensure you are using a thread-safe logger.

使记录器最终和/或静态不会以任何方式影响记录器使用的线程安全性。如果多个线程正在使用记录器实例,请确保您使用的是线程安全的记录器。

In general the logger should be private static final but do not assume that this makes it thread-safe. Most common logging frameworks are thread-safe so if you are using one of these you should be good.

一般来说,记录器应该是私有静态最终的,但不要假设这使它成为线程安全的。大多数常见的日志框架都是线程安全的,因此如果您使用其中之一,您应该会很好。