如何在字符串数组中获取 Logger 值

2022-01-16 00:00:00 java log4j struts2

我使用了 log4j.Logger,并使用 FileAppender 将日志值写入了一个文件.

I used the log4j.Logger and I have written the log value in to a file using the FileAppender.

现在我想在文本区域中显示日志值.如何将记录器值分配给字符串数组?

Now I want to show the log value in a textarea. How can I assign the logger value to an array of Strings?

推荐答案

您可以在 Logger 中添加额外的 Appender.使用 WriterAppender 写入 StringWriter 然后将 TextArea 的内容更改为 StringWriter#toString()

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);
    TextArea textArea = new TextArea();

    logger.error("test");
    //if(stringWriter changed){// compare to old TextArea-content?
      textArea.setText(stringWriter.toString());
    //}
    //System.out.println(stringWriter.toString());
  }

您需要找到一个聪明的方法来更新您的 TextArea,具体取决于 logLevel 以及 StringWriter 的内容是否发生了变化.

you need to find a smart way update your TextArea depending on the logLevel and if the content of the StringWriter changed.

更新:此处提供了一个类似的解决方案.

Update: A comparable solution is presented here.

相关文章