I have a spring bean which has a logger member and I use that logger to log some actions.
Also I have written a test case which uses SpringJUnit4ClassRunner
. I have configured Log4j with a properties file and in each test case I initialize the logger with these properties:
@BeforeClass
public static void init() {
PropertyConfigurator.configure("src/com/config/log4j.properties");
}
when I run a test it gives me a warning
log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
However, the logger in my bean writes messages into the specified location in log4j.properties, i.e. it works fine. Why does log4j gives me such warnings?
I wanted to keep my log4j config out of the default classpath to use different logging with unit tests & production. I worked around it by subclassing SpringJUnit4ClassRunner and using a static class initializer.
// The new test runner
public class JUnit4ClassRunner extends SpringJUnit4ClassRunner {
static {
try {
Log4jConfigurer.initLogging( "classpath:test/log4jconfig.xml" );
}
catch( FileNotFoundException ex ) {
System.err.println( "Cannot Initialize log4j" );
}
}
public JUnit4ClassRunner( Class<?> clazz ) throws InitializationError {
super( clazz );
}
}
The Change to the Test:
@RunWith(JUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration
@Transactional
public class LmpDaoImplTest extends AbstractTransactionalJUnit4SpringContextTests {
...
Now log4j is configured before the Spring test runner is invoked.
I think reason is this code in SpringJUnit4ClassRunner
public SpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
super(clazz);
if (logger.isDebugEnabled()) {
logger.debug("SpringJUnit4ClassRunner constructor called with [" + clazz + "].");
}
this.testContextManager = createTestContextManager(clazz);
}
If you don't want see the warning regarding log4j, Just do as @DN suggested just add log4j.properties file to your application class path, In case if you use maven directory structure add log4j.properties file to (src/main/resources) that will eliminate the warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With