gger.log(Level.WARNING, elements[i].getMethodName());
}
Merlin的魔力: 异常和日志记录(4)
时间:2011-02-02 IBM John Zukowski
缺省情况下,日志记录消息被发送到控制台。可以通过为 LogManager 附加一个 Handler 将日志记录添加到文件,如清单 5 所示。
清单 5. 将日志记录添加到文件try {
LogManager manager = LogManager.getLogManager();
Handler handler = new FileHandler("zuk.log");
manager.addGlobalHandler(handler);
// log it
} catch (IOException logException) {
System.err.println("Logging error");
}
当控制台输出格式不是任何一种易于分析的格式时,文件输出存储为 XML 文档。清单 6 显示了这个示例的这种输出。
清单 6. 样本日志文件输出<?xml version="1.0" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2001-10-30T16:24:23</date>
<millis>1004563463843</millis>
<sequence>0</sequence>
<logger>net.zukowski.ibm</logger>
<level>WARNING</level>
<class>Exceptions</class>
<method>main</method>
<thread>10</thread>
<message>arrayAccess</message>
</record>
<record>
<date>2001-10-30T16:24:24</date>
<millis>1004563464015</millis>
<sequence>1</sequence>
<logger>net.zukowski.ibm</logger>
<level>WARNING</level>
<class>Exceptions</class>
<method>main</method>
<thread>10</thread>
<message>main</message>
</record>
</log>
Merlin的魔力: 异常和日志记录(5)
时间:2011-02-02 IBM John Zukowski
完整的示例
清单 7 提供了一个完整的示例以供您试验这些新功能。
清单 7. 完整的示例import java.io.*;
import java.util.logging.*;
public class Exceptions {
private static void fileAccess() throws IOException {
// Fails because prefix is too short
File f = File.createTempFile("x", "y");
}
private static void divZero() {
System.out.println(1/0);
}
private static void arrayAccess(String array[]) {
System.out.println("First: " + array[0]);
}
public static void main(String args[]) {
try {
try {
fileAccess();
} catch (Exception e) {
class TheException extends Exception {
public TheException() {
}
public TheException(String message) {
super(message);
}
public TheException(Throwable throwable) {
super(throwable);
}
public TheException(String message, Throwable throwable) {
super(message, throwable);
}
}
TheException theExc = new TheException("Prefix too short", e);
throw theExc;
}
} catch (Exception cause) {
System.err.println("Cause: " + cause);
System.err.println("OriginalCause: " |