使用 Logger 进行标准输出重定向
Stdout redirection with Logger
我正在尝试将我的输出重定向到文本区域(将使用以下代码将其嵌入 JFrame 的某处
public static void main(String[] args) {
Logger.getLogger(MyClass.class.getName()).info("Test");
final JTextArea x = new JTextArea();
PrintStream printStream = new PrintStream(new OutputStream(){
@Override
public void write(int b) throws IOException {
x.append(String.valueOf((char)b));
x.setCaretPosition(x.getDocument().getLength());
}
});
System.setOut(printStream);
System.setErr(printStream);
Logger.getLogger(MyClass.class.getName()).info("Test again");
System.out.println("Another test");
JOptionPane.showMessageDialog(null, x.getText());
}
然而,当最后一行执行时,JOptionPane 文本只有 "Another test"。
当我删除第一个 Logger 行时
Logger.getLogger(MyClass.class.getName()).info("Test");
然后所有内容都重定向到 JTextArea。我怀疑在第一行记录 "Test" 后,class Logger 绑定到控制台输出并且即使标准输出被重定向到 TextArea 也不会放弃。
您的主要方法的第一行 captures the current System.err stream. If you remap the streams before creating the root logger handlers it will work. You could also change the code to create a new ConsoleHandler and add it to the root logger after you have remapped the error stream. Look out for violating the EDT rules of Swing 与您当前的实现。
我正在尝试将我的输出重定向到文本区域(将使用以下代码将其嵌入 JFrame 的某处
public static void main(String[] args) {
Logger.getLogger(MyClass.class.getName()).info("Test");
final JTextArea x = new JTextArea();
PrintStream printStream = new PrintStream(new OutputStream(){
@Override
public void write(int b) throws IOException {
x.append(String.valueOf((char)b));
x.setCaretPosition(x.getDocument().getLength());
}
});
System.setOut(printStream);
System.setErr(printStream);
Logger.getLogger(MyClass.class.getName()).info("Test again");
System.out.println("Another test");
JOptionPane.showMessageDialog(null, x.getText());
}
然而,当最后一行执行时,JOptionPane 文本只有 "Another test"。 当我删除第一个 Logger 行时
Logger.getLogger(MyClass.class.getName()).info("Test");
然后所有内容都重定向到 JTextArea。我怀疑在第一行记录 "Test" 后,class Logger 绑定到控制台输出并且即使标准输出被重定向到 TextArea 也不会放弃。
您的主要方法的第一行 captures the current System.err stream. If you remap the streams before creating the root logger handlers it will work. You could also change the code to create a new ConsoleHandler and add it to the root logger after you have remapped the error stream. Look out for violating the EDT rules of Swing 与您当前的实现。