我想动态创建一个appender并将其添加到一个logger中。然而,使用slf4j似乎不可能实现这一点。我可以将我的appender添加到log4j logger中,但是无法使用slf4j LoggerFactoy检索到该logger。
我想做的事情:我创建了一个测试类(不是jUnit测试),并在构造函数中传递一个logger供测试类使用。每个测试类实例都需要自己的logger和appender,以便将日志保存以后用于HTML报告。
我尝试过的方法(为了简化起见,我创建了一个jUnit测试):
import static org.junit.Assert.assertEquals;
import java.util.LinkedList;
import java.util.List;
import org.apache.logging.log4j.core.LogEvent;
import org.junit.Test;
import org.slf4j.helpers.Log4jLoggerFactory;
import ch.fides.fusion.logging.ListAppender;
public class ListAppenderTest {
@Test
public void test() {
String testName = "test1";
// the log messages are to be inserted in this list
List<LogEvent> testLog = new LinkedList<>();
// create log4j logger
org.apache.logging.log4j.core.Logger log4jlogger = (org.apache.logging.log4j.core.Logger) org.apache.logging.log4j.LogManager
.getLogger("Test:" + testName);
// create appender and add it to the logger
ListAppender listAppender = new ListAppender("Test:" + testName + ":MemoryAppender", testLog);
log4jlogger.addAppender(listAppender);
// get the slf4j logger
org.slf4j.helpers.Log4jLoggerFactory loggerFactory = new Log4jLoggerFactory();
org.slf4j.Logger testLogger = loggerFactory.getLogger("Test:" + testName);
// test it
final String TEST_MESSAGE = "test message";
testLogger.info(TEST_MESSAGE);
assertEquals(1, testLog.size());
LogEvent logEvent = testLog.get(0);
assertEquals(TEST_MESSAGE, logEvent.getMessage().getFormattedMessage() );
}
}
这是我的非常基础的附加器:
package ch.fides.fusion.logging;
import java.util.List;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
public class ListAppender extends AbstractAppender {
private final List<LogEvent> log;
public ListAppender(String name, List<LogEvent> testLog) {
super(name, null, null);
this.log = testLog;
}
@Override
public void append(LogEvent logEvent) {
log.add(new TestLogEvent(logEvent));
}
}
我该怎么做才能让它工作?也许我是从错误的角度来解决问题,但我想避免创建自己的记录器类。非常感谢任何帮助。