将Logger.info放在静态块中 [英] Putting Logger.info in static block
问题描述
我有以下课程
public class MyClass
{
private static final Logger logger = Logger.getLogger(MyClass.class);
static
{
logger.info("some text");
}
}
可以安全地假设到我们到达logger.info
时,log4j系统已初始化并准备发出日志了吗?
Is it safe to assume that by the time we reach logger.info
, the log4j system is initialized and is ready to emit logs?
看来,如果我能够执行Logger.getLogger()
并取回有效的Logger实例,则意味着Log4j已初始化,对吧?
It seems that if I am able to do a Logger.getLogger()
and get back a valid Logger instance, it means that Log4j is initialized, right?
推荐答案
是的.静态初始化程序(即static {}
块和对静态变量的初始分配)均按声明的顺序执行.
Yes, it is. Static initializers (that is, both static {}
blocks and initial assignments to static variables) are executed in the order they are declared.
log4j的默认初始化依赖于log4j类LogManager
中的静态块,该静态块在Logger
类被加载并且在首次使用之前被加载时执行.这就是为什么您的构造起作用的原因.
Default initialization of log4j relies on a static block in a log4j class LogManager
that is executed once Logger
class is loaded, and it is loaded prior to its first use. This is why your construction works.
这篇关于将Logger.info放在静态块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!