Putting Logger.info in static block

喜欢而已 提交于 2019-12-08 19:14:18

问题


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?

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?


回答1:


Yes, it is. Static initializers (that is, both static {} blocks and initial assignments to static variables) are executed in the order they are declared.

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.




回答2:


See this part of the 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. 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.



来源:https://stackoverflow.com/questions/12481605/putting-logger-info-in-static-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!