在String变量中获取消息myLogger.log(e)

时间:2012-05-02 17:07:25

标签: java log4j

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

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

2 个答案:

答案 0 :(得分:2)

您可以编写一个写入StringWriter的log4j appender。看看这篇文章:

How to read log4j output to a web page?

答案 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所述。