Logback + Swing小工具 [英] Logback+Swing in small tool

查看:160
本文介绍了Logback + Swing小工具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要破解一个小工具.它应该读取几个文件并将其转换.现在可以在我的IDE中使用了.对于用户,我想添加一个小的UI,该UI仅显示日志输出.

I need to hack up a small tool. It should read a couple of files and convert them. Right now that works in my IDE. For the user, I'd like to add a small UI which simply shows the log output.

您是否知道可立即使用的Swing附加程序以进行注销?还是将System.out重定向到一个小的UI的东西,只不过是文本字段和关闭"按钮?

Do you know of a ready-to-use Swing appender for logback? Or something which redirects System.out to a little UI with nothing more than a text field and a "Close" button?

PS:我不是在寻找电锯,拼图或莉莉丝.我想要在应用程序中显示日志消息.

PS: I'm not looking for Chainsaw or Jigsaw or Lilith. I want the display of the log messages in the application, please.

推荐答案

您需要编写一个自定义的附加程序类,如下所示:

You need to write a custom appender class like so:

public class MyConsoleAppender extends AppenderBase<ILoggingEvent> {
  private Encoder<ILoggingEvent> encoder = new EchoEncoder<ILoggingEvent>();
  private ByteArrayOutputStream  out     = new ByteArrayOutputStream();

  public MyConsoleAppender() {
     LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
     setContext(lc);
     start();
     lc.getLogger("ROOT").addAppender(this);
  }

  @Override
  public void start() {
     try {
        encoder.init(out);
     } catch (IOException e) {}
     super.start();
  }

  @Override
  public void append(ILoggingEvent event) {
     try {
        encoder.doEncode(event);
        out.flush();
        String line = out.toString(); // TODO: append _line_ to your JTextPane
        out.reset();
     } catch (IOException e) {}
  }
}

您可以将EchoEncoder替换为PatternLayoutEncoder(请参阅logback examples文件夹中的CountingConsoleAppender示例).

You can replace the EchoEncoder with a PatternLayoutEncoder (see CountingConsoleAppender example in the logback examples folder).

编码器会将每个事件写入字节缓冲区,然后您可以提取该字符串并将其写入JTextPane或JTextArea或所需的任何内容.

The encoder will write each event to a byte buffer, which you can then extract a string and write this to your JTextPane or JTextArea, or whatever you want.

这篇关于Logback + Swing小工具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆