我想在String变量中获取此方法myLogger.log(e)的输出,以便能够使用Junit进行测试。
myLogger.log(e);
String s= ????
assertEqual(expected,s);
答案 0 :(得分:2)
您可以编写一个写入StringWriter的log4j appender。看看这篇文章:
答案 1 :(得分:0)
您可以在Logger中添加额外的Appender。使用WriterAppender写入StringWriter,然后将TextArea的内容更改为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);
}
如here所述。