Is there an appender for log4j that only stores a list of the logging events (to be used in unit tests, to verify no error logs were written) ?
There is a MemoryAppender, but it's not part of the standard log4j library.
You could easily write your own, But if you are only using them for unit tests I would probably mock the Logger and assert no calls are made to it. Override the getLogger() method in the target class or set the mock Logger directly on the type.
Using Jmock (example from memory, sorry for any errors):
public void testDoFoo() {
Mockery mockery = new Mockery();
Logger mockLogger = mockery.mock(Logger.class);
Foo foo = new Foo();
foo.setLogger(mockLogger);
mockery.checking(new Expectations() {
{
never(mockLogger).debug(with(any(String.class));
}
};
...
//do the actual test.
//assert the mock type has never been called.
mockery.assertIsSatisfied();
}
I don't believe there is. You can write your own easily, though. Here's a suitable tutorial.
This is an example implementation of a logger appender, that stores all the events in memory (in a StringBuilder
); the contents can then be retrieved with getResult
:
package apackage;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
/**
* Records logging events in a String.
*
* @author Lorenzo Bettini
*
*/
public class InMemoryLoggerAppender extends AppenderSkeleton {
private StringBuilder builder = new StringBuilder();
@Override
public void close() {
// nothing to close
}
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(LoggingEvent event) {
builder.append(
event.getLevel() + ": " + event.getMessage().toString()
+ System.lineSeparator());
}
public String getResult() {
return builder.toString();
}
}
You then have to add this appender to an existing Logger
, for example (MyClass
is the class that uses a Logger
to log events you want to capture):
InMemoryLoggerAppender appender = new InMemoryLoggerAppender();
Logger log = Logger.getLogger(MyClass.class);
log.addAppender(appender);
© 2022 - 2024 — McMap. All rights reserved.