1
votes

I'm using Spring Framework (4.1.0) to build sample application where I can play with Unit Tests.

My test class use @RunWith(SpringJUnit4ClassRunner.class) annotation which logs WARNS

log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).

log4j:WARN Please initialize the log4j system properly.

in console because I'm not using log4j2 file based configuration.

My test class also use @ContextConfiguration(classes = { AppConfig.class, ServletConfig.class }) annotation to point to context where I try to initialize log4j2.

Question: How can I properly initialize log4j2 to use it with SpringJUnit4ClassRunner without file based configuration ?

Other Java based config approaches are welcome :)

3
I place a log4j.xml file in my test/resources folder. - Hannes
And for the record the SpringJUnit4ClassRunner has nothing to do with log4j. - Hannes
@Hannes, correct me if I'm wrong but in source of SpringJUnit4ClassRunner at the beginning we have private static final org.apache.commons.logging.Log logger; which means it's related with log4j2. - xyz
That's the commons-logging and will look up the logging mechanism you use. So if it finds a log4 lib, it will use this. If nothing is found it will use sysout. - Hannes
You're right, but the question is still valid then. - xyz

3 Answers

1
votes

You can initialize Log4j2 programmatically. There is an example here on the Log4j2 website under the section 'Programatically Adding to the Current Configuration' showing how to add an appender.

0
votes

Add the following file content as log4j.xml to your classpath root:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'> 
   <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/>
      </layout>
   </appender>
   <root>
      <level value="INFO"/>
      <appender-ref ref="consoleAppender"/>
   </root>
</log4j:configuration>

This should configure log4j. However, check you lib path. There must be a log4j jar anywhere.

0
votes

You may have both log4j and log4j2 jars on your classpath.

So SpringJUnit4ClassRunner is trying to use log4j instead of log4j2. Remove the log4j jar and use log4j-1.2-api instead.

http://logging.apache.org/log4j/2.x/faq.html#which_jars