这一章介绍的是一个小组件,日志记录器。首先这个组件是由Logger接口定义的,我们来看一下接口定义的日志级别:
/**
* Verbosity level constants for log messages that may be filtered
* by the underlying logger.
*/
public static final int FATAL = Integer.MIN_VALUE;
public static final int ERROR = 1;
public static final int WARNING = 2;
public static final int INFORMATION = 3;
public static final int DEBUG = 4;
然后来看一下实现了Logger接口的LoggerBase类重要的方法:
public void setVerbosityLevel(String verbosity) {
if ("FATAL".equalsIgnoreCase(verbosity))
this.verbosity = FATAL;
else if ("ERROR".equalsIgnoreCase(verbosity))
this.verbosity = ERROR;
else if ("WARNING".equalsIgnoreCase(verbosity))
this.verbosity = WARNING;
else if ("INFORMATION".equalsIgnoreCase(verbosity))
this.verbosity = INFORMATION;
else if ("DEBUG".equalsIgnoreCase(verbosity))
this.verbosity = DEBUG;
}
这是设置日志级别的方法,除了log方法,其他Logger接口的方法都被实现了,log方法不实现的原因是,日志记录器要定制。
接下来是LoggerBase的子类fileLogger。它将从关联容器收到的信息写到文件中,每个信息可以选择性地加上时间戳。在第一次实例化时,该类的实例会创建一个文件,该文件带有日期信息。如果日期改变了,他会创建一个新的文件并把信息写在里面。类的实例允许在日志文件的名字上添加前缀和后缀。
public void log(String msg) {
// Construct the timestamp we will use, if requested
Timestamp ts = new Timestamp(System.currentTimeMillis());
String tsString = ts.toString().substring(0, 19);
String tsDate = tsString.substring(0, 10);
// If the date has changed, switch log files
if (!date.equals(tsDate)) {
synchronized (this) {
if (!date.equals(tsDate)) {
close();
date = tsDate;
open();
}
}
}
// Log this message, timestamped if necessary
if (writer != null) {
if (timestamp) {
writer.println(tsString + " " + msg);
} else {
writer.println(msg);
}
}
}
...
/**
* Close the currently open log file (if any)
*/
private void close() {
if (writer == null)
return;
writer.flush();
writer.close();
writer = null;
date = "";
}
/**
* Open the new log file for the date specified by <code>date</code>.
*/
private void open() {
// Create the directory if necessary
File dir = new File(directory);
if (!dir.isAbsolute())
dir = new File(System.getProperty("catalina.base"), directory);
dir.mkdirs();
// Open the current log file
try {
String pathname = dir.getAbsolutePath() + File.separator +
prefix + date + suffix;
writer = new PrintWriter(new FileWriter(pathname, true), true);
} catch (IOException e) {
writer = null;
}
}