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?
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.
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.