简体   繁体   English

将Logger.info放在静态块中

[英]Putting Logger.info in static block

I have the following class 我有以下课程

public class MyClass
{
    private static final Logger logger = Logger.getLogger(MyClass.class);

    static
    {
        logger.info("some text");
    }
}

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.info ,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? 看来,如果我能够执行Logger.getLogger()并取回有效的Logger实例,则意味着Log4j已初始化,对吗?

Yes, it is. 是的。 Static initializers (that is, both static {} blocks and initial assignments to static variables) are executed in the order they are declared. 静态初始化器(即, static {}块和对静态变量的初始分配)均按声明的顺序执行。

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. log4j的默认初始化依赖于log4j类LogManager中的静态块,该静态块在Logger类装入后即被执行,并且在首次使用之前装入。 This is why your construction works. 这就是为什么您的构造起作用的原因。

See this part of the JLS . 请参阅JLS的这一部分。 It talks about what happens when you initialise a class. 它讨论初始化类时会发生什么。 This part talks about static initialisers. 部分讨论静态初始化程序。 In answer to your question then AFAIK the static blocks are executed in the order they occur. 然后回答您的问题,然后AFAIK静态块将按照它们出现的顺序执行。 They will be executed when the class is loaded which can happen when you create an instance of it or access a static var/method of it. 它们将在加载类时执行,创建类的实例或访问其静态var /方法时可能发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM