我正在尝试将一个小测试用例(确保我们的日志记录按预期工作)从log4j-1.6迁移到log4j-2.6。我们正在做的是传递一个映射并将其记录在Debug级别下,并验证loggingEvent是否为Debug,并为期望的呈现消息进行断言。我们这样做
final ArgumentCaptor<LoggingEvent> loggingEventCaptor = ArgumentCaptor.forClass(LoggingEvent.class);
verify(mockAppender).doAppend(loggingEventCaptor.capture());
final LoggingEvent loggingEvent = loggingEventCaptor.getValue();
assertEquals(Level.DEBUG, loggingEvent.getLevel());
assertEquals("ExpectedMessage", loggingEvent.getRenderedMessage());
但后来知道appender和loggingEvents不在log4j2中。但我找不到实现这个目标的方法。是否可以使用log4j2?
答案 0 :(得分:3)
经过长时间的研究,我解决了这个问题。在src lik
中的tst和属性文件中添加了自定义的appender@Plugin(name = "TestAppender", category = "Core", elementType = "apender", printObject = true)
public class TestAppender extends AbstractAppender {
private List<String> messages = new ArrayList<String>();
protected TestAppender(String name, Filter filter, Layout<? extends Serializable> layout) {
super(name, filter, layout);
}
@Override
public void append(LogEvent event) {
getMessages().add(event.getMessage().toString());
}
public static TestAppender createAppender(@PluginAttribute("name") String name,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginElement("Filter") final Filter filter,
@PluginAttribute("otherAttribute") String otherAttribute) {
if (name == null) {
LOGGER.error("No name provided for TestAppender");
return null;
}
if (layout == null) {
layout = PatternLayout.createDefaultLayout();
}
return new TestAppender(name, filter, layout);
}
public List<String> getMessages() {
return messages;
}
public void setMessages(List<String> messages) {
this.messages = messages;
}
}
这里我将我的日志级别设置为Debug并编写了一个自定义appender,它实际上创建了一个appender并设置并获取日志消息
@Before
public void setUp() {
org.apache.logging.log4j.core.Logger logger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
PatternLayout layout = PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%t] %-5level %logger{1} - %msg%n%ex",
null, null, null, Charset.forName("GBK"), false, true, null, null);
testAppender = TestAppender.createAppender("TestAppender", layout, null, "true");
testAppender.start();
logger.getContext().getConfiguration().addLoggerAppender(logger, testAppender);
}
在我的实际测试中,我在setup方法中初始化并附加了一个appender
assertEquals(Level.DEBUG, LogManager.getRootLogger().getLevel());
assertEquals(
"[Request headers: [{key: one, values: [one1, one2]}, {key: two, values: []}, {key: three, values: [three]}]]",
testAppender.getMessages().toString());
并以这种方式断言。
Knit
这是一个漫长的过程。但它对我有用。经过长时间的研究,我想出了这个。如果有的话,我正在寻找更好,更简单的方法。
注意:我根据服务目的从各种博客中复制了此代码。