mple");
Handler handler = LoggingWindowHandler.getInstance();
logger.addHandler(handler);
}
logger.log(Level.WARNING, t.getName(), e);
}
}
这里创建的定制 Handler 的类型为 LoggingWindowHandler ,该类型的定义在清单 5 中。处理程序使用了一个支持类 LoggingWindow ,该类将异常显示在屏幕上。 清单 6 中显示了该类的定义。 Handler 的 public void publish(LogRecord record) 方法实现了一些重要操作。其余操作大部分只与配置有关。
清单 5. LoggingWindowHandler 的定义
import java.util.logging.*;
public class LoggingWindowHandler extends Handler {
private static LoggingWindow window;
private static LoggingWindowHandler handler;
private LoggingWindowHandler() {
configure();
window = new LoggingWindow("Logging window...", 400, 200);
}
public static synchronized LoggingWindowHandler getInstance() {
if (handler == null) {
handler = new LoggingWindowHandler();
}
return handler;
}
/**
* Get any configuration properties set
*/
private void configure() {
LogManager manager = LogManager.getLogManager();
String className = getClass().getName();
String level = manager.getProperty(className + ".level");
setLevel((level == null) ? Level.INFO : Level.parse(level));
String filter = manager.getProperty(className + ".filter");
setFilter(makeFilter(filter));
String formatter =
manager.getProperty(className + ".formatter");
setFormatter(makeFormatter(formatter));
}
private Filter makeFilter(String name) {
Filter f = null;
try {
Class c = Class.forName(name);
f = (Filter)c.newInstance();
} catch (Exception e) {
if (name != null) {
System.err.println("Unable to load filter: " + name);
}
}
return f;
}
private Formatter makeFormatter(String name) {
Formatter f = null;
try {
Class c = Class.forName(name);
f = (Formatter)c.newInstance();
} catch (Exception e) {
f = new SimpleFormatter();
}
return f;
}
// Overridden abstract Handler methods
public void close() {
}
public void flush() {
}
/**
* If record is loggable, format it and add it to window
*/
public void publish(LogRecord record) {
String message = null;
if (isLoggable(record)) {
try {
message = getFormatter().format(record);
} catch (Exception e) {
reportError(null, e, ErrorManager.FORMAT_FAILURE);
return;
}
try {
window.addLogInfo(message);
} catch (Exception e) {
reportError(null, e, ErrorManager.WRITE_FAILURE);
}
}
}
}
驯服Tiger: 线程中的默认异常处理(3)
时间:2011-01-31 John Zukowski
清单 6. LoggingWindow 的定义
import java.awt.*;
import javax.swing.*;
public class LoggingWindow extends JFrame {
private JTextArea textArea;
public LoggingWindow(String title, final int width,
|