Tomcat源码分析(六)--日志记录器和国际化(一)

2014-11-24 08:41:39 · 作者: · 浏览: 0

日志记录器挺简单的,没有很多东西,最主要的就是一个Logger接口:

[java]
public interface 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;
public Container getContainer();
public void setContainer(Container container);
public String getInfo();
public int getVerbosity();
public void setVerbosity(int verbosity);
public void addPropertyChangeListener(PropertyChangeListener listener);
public void log(String message);
public void log(Exception exception, String msg);
public void log(String message, Throwable throwable);
public void log(String message, int verbosity);
public void log(String message, Throwable throwable, int verbosity);
public void removePropertyChangeListener(PropertyChangeListener listener);
}
只要实现Logger就能有一个自己的日志记录器,其中setContainer是把日志记录器跟具体的容器关联,setVerbosity是设置日志的级别,log是具体的日志记录函数。FATAL,ERROR,WARNING,INFORMATION,DEBUG代表日志记录的五个级别,看单词就能明白意思。这里主要讲解一下FileLogger类,这是Tomcat的其中一个日志记录器,它把日志记录在一个文件中,FileLogger的启动方法和关闭仅仅是出发一个生命周期事件,并不做其他的事情:
[java]
public void start() throws LifecycleException {

// Validate and update our current component state
if (started)
throw new LifecycleException
(sm.getString("fileLogger.alreadyStarted"));
lifecycle.fireLifecycleEvent(START_EVENT, null);//触发生命周期事件
started = true;

}
这里有一行代码sm.getString("fileLogger.alreadyStarted"),牵涉到国际化的问题,等下再说这个问题。现在先看日志记录器,FileLogger的open方法打开一个文件用来记录日志:
[java]
private void open() {

// Create the directory if necessary
File dir = new File(directory);//directory等于logs,即在文件夹logs下新建日志文件
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;
}

}
这里得到一个PrintWriter的输出流writer,在log方法记录日志的时候会用到,下面看log方法:
[java]
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);
}
}

}


writer.println把时间和日志信息写进日志文件中。当然,这个日志记录器一般是给Tomcat自己用的,我们也可以实现Logger接口,然后重写它的open方法(打开我们自己的日志文件)和log方法(用来在我们自己的日志文件中记录日志信息)。
现在再来看刚才提到的代码sm.getString("fileLogger.alreadyStarted")。在理解这句代码前先看一个jdk的类ResourceBun