log4j.rootLogger is at the top of all the logger hierarchy, just like we have Object in java classes. So whenever you are logging and there is no match with a logger configuration, root logger configuration will be used.

log4j.rootLogger example

Let’s understand this with a simple example. Suppose we have a log4j.properties file like below.


#Define root logger options
log4j.rootLogger=DEBUG, console
#Define console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
logrj.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-5p %c{1} - (%F:%L) %m%n
#Define loggers
log4j.logger.com.journaldev.log4j.main=ERROR, console
#setting additivity
log4j.additivity.com.journaldev.log4j.main=false

And here is a simple java program in package com.journaldev.log4j.main corresponding to logger defined above.


package com.journaldev.log4j.main;
import org.apache.log4j.Logger;
public class Log4jExample {
	private final static Logger logger = Logger.getLogger(Log4jExample.class);
	public static void main(String[] args) {
		logger.trace("My Trace Log");
		logger.debug("My Debug Log");
		logger.info("My Info Log");
		logger.warn("My Warn Log");
		logger.error("My error log");
		logger.fatal("My fatal log");
	}
}

Below image shows the output when we run it.

logger.rootLogger-example

Now below is the output when I change the package declaration to com.journaldev.log4j.main1, so that it doesn’t match with any of the defined logger.

logger.rootLogger-example

Here the root logger configuration is being used, i.e logging level as DEBUG and a single appender “console”.

So is it required to define log4j.rootLogger always?

No, log4j doesn’t give you any warning or any exception if you won’t define it. Unless a Logger instance is trying to use it.

So if I comment the root logger configuration above and my java program is in com.journaldev.log4j.main package, then a logger is defined for it and everything works fine.

But if I am running my java program from com.journaldev.log4j.main1 package for which no logger is defined, it tries to look for root logger configuration and don’t find it. So it prints below warning message to console.


log4j:WARN No appenders could be found for logger (com.journaldev.log4j.main1.Log4jExample).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See https://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Finally, how do we define the same thing in log4j.xml file?

Below is the XML based configuration with same thing as above log4j.properties file.


<root>
	<priority value="DEBUG" />
	<appender-ref ref="console" />
</root>

That’s all for log4j root logger configuration significance and usage.

By admin

Leave a Reply

%d bloggers like this: