我想在字符串变量中获取此方法 myLogger.log(e) 的输出,以便能够使用 Junit 进行测试。
myLogger.log(e);
String s= ????
assertEqual(expected,s);
您可以编写一个写入 StringWriter 的 log4j appender。看看这个帖子:
You can add an additional Appender to your Logger. Use a WriterAppender to write to a StringWriter then you change the content of your TextArea to the value of StringWriter#toString()
public static void main(String[] args) {
Logger logger = Logger.getLogger("logger");
Layout layout = new PatternLayout();
StringWriter stringWriter = new StringWriter();
WriterAppender writerAppender = new WriterAppender(layout, stringWriter);
logger.addAppender(writerAppender);
logger.error("test");
String string = stringWriter.toString();
System.out.println(string);
}
as described here.