package logger;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.*;
import javax.swing.*;
public class LoggingImageViewer {
public static void main(String[] args) {
if(System.getProperty("java.util.logging.config.class") == null
&& System.getProperty("java.util.logging.config.file") == null) {
try {
Logger.getLogger("logger").setLevel(Level.ALL);
final int LOG_ROTATION_COUNT = 10;
Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
Logger.getLogger("logger").addHandler(handler);
} catch (IOException e) {
Logger.getLogger("logger").log(Level.SEVERE, "Can't create log file handler.", e);
}
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Handler windowHandler = new WindowHandler();
windowHandler.setLevel(Level.ALL);
Logger.getLogger("logger").addHandler(windowHandler);
JFrame frame = new ImageViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Logger.getLogger("logger").fine("Showing frame");
frame.setVisible(true);
}
});
}
}
class WindowHandler extends StreamHandler {
public WindowHandler() {
frame = new JFrame();
final JTextArea output = new JTextArea();
output.setEditable(false);
frame.setSize(200, 200);
frame.add(new JScrollPane(output));
frame.setFocusableWindowState(false);
frame.setVisible(true);
//安装一个流,该流的write方法将流显示输出到output
setOutputStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
}
@Override
public void write(byte[] b, int off, int len) {
output.append(new String(b, off, len));
}
});
}
//强制刷新
@Override
public void publish(LogRecord record) {
if(!frame.isVisible()) {
return;
}
super.publish(record);
flush();
}
private JFrame frame;
}