The examples in this post were very helpful, but I found them little confusing.
So I am adding a simplified version for the above with some minor changes.
- I am adding my appender to the root logger.
This way, and assuming additively is true by default, I will not need to worry about losing my events due to logger hierarchy. Make sure this meet your log4j.properties file configuration.
- I am overriding append and not doAppend.
Append in AppenderSkeleton deals with level filtering, so I do not want to miss that.
doAppend will call append if the level is right.
public class TestLogger {
@Test
public void test() {
TestAppender testAppender = new TestAppender();
Logger.getRootLogger().addAppender(testAppender);
ClassUnderTest.logMessage();
LoggingEvent loggingEvent = testAppender.events.get(0);
//asset equals 1 because log level is info, change it to debug and
//the test will fail
assertTrue("Unexpected empty log",testAppender.events.size()==1);
assertEquals("Unexpected log level",Level.INFO,loggingEvent.getLevel());
assertEquals("Unexpected log message"
,loggingEvent.getMessage().toString()
,"Hello Test");
}
public static class TestAppender extends AppenderSkeleton{
public List<LoggingEvent> events = new ArrayList<LoggingEvent>();
public void close() {}
public boolean requiresLayout() {return false;}
@Override
protected void append(LoggingEvent event) {
events.add(event);
}
}
public static class ClassUnderTest {
private static final Logger LOGGER =
Logger.getLogger(ClassUnderTest.class);
public static void logMessage(){
LOGGER.info("Hello Test");
LOGGER.debug("Hello Test");
}
}
}
log4j.properties
log4j.rootCategory=INFO, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d %p [%c] - %m%n
# un-comment this will fail the test
#log4j.logger.com.haim.logging=DEBUG