1

我想在字符串变量中获取此方法 myLogger.log(e) 的输出,以便能够使用 Junit 进行测试。

myLogger.log(e);
String s= ????
assertEqual(expected,s);
4

2 回答 2

2

您可以编写一个写入 StringWriter 的 log4j appender。看看这个帖子:

如何将 log4j 输出读取到网页?

于 2012-05-02T17:24:30.820 回答
0

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.

于 2012-10-26T10:12:10.440 回答